UIScrollView wrong offset with Auto Layout

前端 未结 7 980
逝去的感伤
逝去的感伤 2020-12-12 22:19

I have a fairly simple view configuration:

A UIViewController, with a child UIScrollView and a UIImageView in this UIScr

7条回答
  •  抹茶落季
    2020-12-12 23:00

    Yeah, something strange happened with UIScrollView in pure autolayout environment. Re-reading the iOS SDK 6.0 release notes for the twentieth time I found that:

    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.

    Solution

    Connect your subview to the outer view. In another words, to the view in which scrollview is embedded.

    As IB does not allow us set up constraints between the imageView and a view outside the scroll view’s subtree, such as the scroll view’s superview then I've done it in code.

    - (void)viewDidLoad {
        [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
        [self.view removeConstraints:[self.view constraints]];
        [self.scrollView removeConstraints:[self.scrollView constraints]];
        [self.imageView removeConstraints:[self.imageView constraints]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_scrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_scrollView)]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_scrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_scrollView)]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_imageView(700)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView)]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_imageView(1500)]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView)]];
    }
    

    And vau! It works!

提交回复
热议问题