UIScrollView with scaled UIImageView using autolayout

后端 未结 3 2436
广开言路
广开言路 2021-02-20 04:51

\"UIScrollView

Consider a UIScrollView with a single subview. The subview is an

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-20 05:30

    Under the autolayout regime, ideally the UIScrollView contentSize is solely determined by the constraints and not set explicitly in code.

    So in your case:

    • Create constraints to pin the subview to the UIScrollView. The constraints have to ensure the margin between the subview and the scroll view are 0. I see that you have already tried this.

    • Create a height and a width constraint for your subview. Otherwise, the intrinsic size of the UIImageView determines its height and width. At design time, this size is only a placeholder to keep Interface Builder happy. At run time, it will be set to the actual image size, but this is not what you want.

    • During viewDidLayoutSubviews, update the constraints to be actual content size. You can either do this directly by changing the constant property of the height and width constraint, or calling setNeedsUpdateConstraints and overriding updateConstraints to do the same.

    This ensures that the system can derive contentSize solely from constraints.

    I've done the above and it works reliably on iOS 6 and 7 with a UIScrollView and a custom subview, so it should work for UIImageView too. In particular if you don't pin the subview to the scroll view, zooming will be jittery in iOS 6.

    You may also try creating height and width constraints that directly reference a multiple of the height and width of the scroll view, but I haven't tried this other approach.

提交回复
热议问题