Is it possible to have a UIImageView inside of a UIScrollView zoom in and out, but stick to center with Auto Layout?

后端 未结 2 1196
孤街浪徒
孤街浪徒 2021-02-15 13:14

Long story short, I\'m trying to build functionality similar to Photos.app.

I have a UIScrollView with a UIImageView inside of it set up in the Storyboard. Zooming works

2条回答
  •  再見小時候
    2021-02-15 13:38

    When using Autolayout the calls to setFrames are not taking effects, thats why the imageView is not centered in your scrollView.

    That being said, in order to achieve the center effect you can choose between:

    1. The easiest way is to set translatesAutoresizingMaskIntoConstraints to YES for your imageView in ViewDidLoad, that will translate the calls to setFrame: to new constraints based on your imageView autoresizingMask. But you should make sure that the new constraints are satisfied with the ones that you set in your storyboard (in your case none).

    2. In your scrollViewDidZoom: method add directly the constraints to center your imageView

    -

     [self.imageView addConstraint:[NSLayoutConstraint constraintWithItem:self.imageView
           attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual
           toItem:self.scrollView attribute:NSLayoutAttributeCenterX multiplier:1.0
           constant:0]];
    
     [self.imageView addConstraint:[NSLayoutConstraint constraintWithItem:self.imageView
           attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual
           toItem:self.scrollView attribute:NSLayoutAttributeCenterX multiplier:1.0 
           constant:0]];
    

提交回复
热议问题