Matching subview's width to it's superview using autolayout

后端 未结 2 1144
借酒劲吻你
借酒劲吻你 2020-12-16 03:02

Goal:

Have a UIWebView be the same width as it\'s superview, which is a UIScrollView, using autolayout constraints.

2条回答
  •  囚心锁ツ
    2020-12-16 03:26

    Improving on Rob's answer, as requested.

    As Rob already mentioned, UIScrollViews have peculiar behavior under Auto Layout.

    What is of interest in this case is the fact that the scrollView total width is determined by using its subviews total width. So while the scrollView already asks the webView for its width, you're telling the webView to also ask the scrollView for its width. That's why it doesn't work. One is asking another, and no one knows the answer. You need another reference view to use as a constraint for the webView, and then the scrollView will also be able to successfully ask about its expected width.

    An easy way this could be done: create another view, containerView, and add the scrollView as a subview to that. Then set the proper constraints for containerView. Let's say you wanted the scrollView centered on a viewController, with some padding on the edges. So do it for the containerView:

    NSDictionary *dict = NSDictionaryOfVariableBindings(containerView);
    [self.view addConstraints:[NSLayoutConstraints constraintsWithVisualFormat:@"H|-(100)-[containerView]-(100)-|" options:0 metrics:0 views:dict];
    [self.view addConstraints:[NSLayoutConstraints constraintsWithVisualFormat:@"V|-(100)-[containerView]-(100)-|" options:0 metrics:0 views:dict];
    

    Then you can proceed adding the webView as a subview to the scrollView and setting its width:

    NSLayoutConstraint *makeWidthTheSameAsScrollView =[NSLayoutConstraint
                                                           constraintWithItem:self.questionWebView
                                                           attribute:NSLayoutAttributeWidth
                                                           relatedBy:0
                                                           toItem:containerView
                                                           attribute:NSLayoutAttributeWidth
                                                           multiplier:1.0
                                                           constant:0];
    
    [self.view addConstraint:makeWidthTheSameAsScrollView];
    

    This would make the scrollview as large and tall as the webView, and they both would be placed as intended (with the constraints set on containerView).

提交回复
热议问题