Autolayout constraint that uses UIScrollview contentSize

流过昼夜 提交于 2019-12-09 23:47:41

问题


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];


}


来源:https://stackoverflow.com/questions/26699565/autolayout-constraint-that-uses-uiscrollview-contentsize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!