代码之家  ›  专栏  ›  技术社区  ›  Pangu

如何在UIScrollView中缩放UIImageView?

  •  3
  • Pangu  · 技术社区  · 10 年前

    我在UIScrollView中有一个UIImageView,我可以垂直滚动,但不能水平滚动,因为我设置了内容大小。这正是我想要的。

    然而,我似乎无法放大和缩小。我设置了最小和最大缩放比例,但它不起作用。

    有人能告诉我为什么吗?

    谢谢

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        //self.scrollView.scrollEnabled = YES;
    
        CGSize scrollableSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
        [self.scrollView setContentSize:scrollableSize];
    
        UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.png"] ];
        tempImageView.frame = CGRectMake(0, 0, self.scrollView.frame.size.width, self.view.frame.size.height);
    
        self.scrollView.backgroundColor = [UIColor blackColor];
        self.scrollView.minimumZoomScale = 1.0  ;
        self.scrollView.maximumZoomScale = tempImageView.image.size.width / self.scrollView.frame.size.width;
        self.scrollView.zoomScale = 1.0;
        self.scrollView.delegate = self;
    
        [self.scrollView addSubview:tempImageView];
    }
    
    3 回复  |  直到 10 年前
        1
  •  4
  •   Armin    10 年前

    您必须实现以下缩放委托方法:

    -(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
    {
        return self.imageView;
    }
    

    并确保添加 self.imageView 到您的 self.scrollView 相反 应该是这样的:

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        CGSize scrollableSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
        [self.scrollView setContentSize:scrollableSize];
    
        self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.png"] ];
        self.imageView.frame = CGRectMake(0, 0, self.scrollView.frame.size.width, self.view.frame.size.height);
    
        self.scrollView.backgroundColor = [UIColor blackColor];
        self.scrollView.minimumZoomScale = 1.0  ;
        self.scrollView.maximumZoomScale = self.imageView.image.size.width / self.scrollView.frame.size.width;
        self.scrollView.delegate = self;
    
        [self.scrollView addSubview:self.imageView];
    }
    
        2
  •  2
  •   foundry    10 年前

    要使缩放生效,您需要提供一个代理方法,该方法返回您希望缩放的视图:

    - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
       return self.imageView
    }
    

    您还需要保持分配 tempImageView 指向属性,以便您可以在此处引用它。如果您不想在属性中保留它,则需要其他方法来标识视图,例如。 scrollView.subviews[0] 如果它是唯一的子视图。

        3
  •  -1
  •   Verdant    10 年前

    试试这个试试这个

    [scroll setUserInteractionEnabled:YES];

    你的最大缩放比例很奇怪。尝试使用2,0进行测试。