Embed ImageView in ScrollView with Auto Layout on iOS 6

前端 未结 2 1859
感情败类
感情败类 2020-12-13 07:28

I am trying to make very simple element with new iOS 6 SDK with auto layout. I have an ImageView and Embed it in ScrollView. (everything build with Interface Builder). The .

相关标签:
2条回答
  • 2020-12-13 07:40

    Autolayout can be very confusing at first. You actually don't want to set the contentSize of the scrollview anywhere. With a pure autolayout approach the scrollview sets its own content size. See the section on autolayout and UIScrollView in the iOS 6 release notes:

    The constraints on the subviews of the scroll view must result in a size to fill, which is then interpreted as the content size of the scroll view. (This should not be confused with the intrinsicContentSize method used for Auto Layout.)

    Note that this means that the constraints on the subviews of the scrollview must set explicit widths and heights and not use widths that vary based on aspects of the scrollview.

    The second error here is that you set the frame of the UIImageView to the size of the image. With autolayout this is also unnecessary. The UIImageView actually has an intrinsicContentSize which is the size of the underlying image. (To change this you should set constraints for width and height with a high priority) That means that with auto layout to place an image in a scrollview and have it scroll the correct code should be the following:

    ** nothing at all!!! **
    

    But theres still something you need to watch out for that could cause you to have an image that appears not to scroll and the hint is in the aforelinked release notes:

    Note that you can make a subview of the scroll view appear to float (not scroll) over the other scrolling content by creating constraints between the view and a view outside the scroll view’s subtree, such as the scroll view’s superview.

    i.e. if you set constraints in interface builder and constrain the image view to a view above the scrollview in the hierarchy it will affect how the view appears to scroll. Mad!

    Happy Coding...

    0 讨论(0)
  • 2020-12-13 07:57

    I just encountered the same issue in a tutorial that I was updating. I attempted programmatically deleting constraints, cursing, and banging my head against the wall - no luck.

    About 5 minutes ago, however, I tried something that had fixed another issue I encountered, and, ta da! UIScrollView is working again! The solution was to move the old code that sets the UIScrollView contentSize property into an implementation of viewDidAppear, rather than viewDidLoad:

    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        self.theScroller.contentSize=CGSizeMake(200.0,2000.0);
    }
    

    I hope this helps someone else encountering some of the headaches that have appeared with Auto Layout.

    0 讨论(0)
提交回复
热议问题