繁体   English   中英

如何在UIScrollView中缩放UIImageView?

[英]How to zoom a UIImageView within a UIScrollView?

我在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];
}

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

-(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];
}

要使缩放工作,您需要提供一个委托方法,该方法返回您希望缩放的视图:

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

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

试试这个尝试一下

[scroll setUserInteractionEnabled:YES];

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM