Autolayout constraint that uses UIScrollview conte

2019-04-16 20:39发布

问题:

I have a UIView inside a UIScrollView. I can easily pin the height to the UIScrollView's frame height.

How do I add a constraint that pins to the UIScrollView's contentSize instead?

Thanks!

回答1:

UIScrollView have dynamic constraints, left, top, width and height are generated at runtime. If you put a UIView inside a UIScrollview and Pin fixed constraints in Interface Builder it will generate an error because the parameters are relative to Superview/Container View.

You can try some workarounds:

1- Add UIView constraints Programmatically

http://www.thinkandbuild.it/learn-to-love-auto-layout-programmatically/

2- Manually resize your view bounds in initWithFrame function inside a UIView Subclass

Please give me any feedback about your progress.



回答2:

The answer "Adding constraints programatically" is correct but it was a little light on detail for me to accept it as the full answer.

Here's how I did it!

  1. Remove all storyboard constraints on the WebView
  2. Add a Placeholder constraint in storyboard for the constraint that you will add with code. This step is very important (and easily missed) or you will get an error about conflicting constraints.
  3. Add code to webviewDidFinishLoad delegate method

--Code--

- (void)webViewDidFinishLoad:(UIWebView *)webView {

    _scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width, _headerImageView.frame.size.height + webView.scrollView.contentSize.height);



    _webView.translatesAutoresizingMaskIntoConstraints = NO;

    NSDictionary *viewsDictionary = @{@"myWebView":_webView};

    NSString *constraintsString = [NSString stringWithFormat:@"V:[myWebView(%i)]", (int)_scrollView.contentSize.height];


    NSArray *constraint_H = [NSLayoutConstraint constraintsWithVisualFormat:constraintsString options:0 metrics:nil views:viewsDictionary];

    [_webView addConstraints:constraint_H];


}