如何在UIScrollView中缩放UIImageView?

时间:2015-01-24 23:32:23

标签: ios objective-c uiscrollview uiimageview

我在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 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

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

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

您还需要暂时将tempImageView分配给某个媒体资源,以便您在此处参考。如果您不想在某个媒体资源中依赖它,则需要采用其他方式来识别该视图,例如: scrollView.subviews[0]如果它是唯一的子视图。

答案 2 :(得分:-1)

试试这个试试这个

[scroll setUserInteractionEnabled:YES];

你的最大缩放比例很奇怪。尝试用2.0来测试。