使用autolayout将子视图的宽度与其超级视图匹配

drc*_*drc 9 uiwebview uiscrollview ios autolayout

目标:

有一个UIWebView具有相同的宽度,因为它是上海华,这是一种UIScrollView使用自动布局约束.

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

[self.view addConstraint:makeWidthTheSameAsScrollView];

 NSLog(@"The width of questionWebView *AFTER* adding the constrain is: %f", self.questionWebView.frame.size.width);
 NSLog(@"The width of scrollView *AFTER* adding the constrain is: %f", self.masterScrollView.frame.size.width);
Run Code Online (Sandbox Code Playgroud)

目前的结果

当我记录self.questionWebView(the UIWebView)的宽度时,当应用autolayout约束时,它的宽度不会改变.

问题

  • 这是正确的方法吗?
  • 我究竟做错了什么?

PS我知道这是对苹果的建议放置UIWebView在一个UIScrollView,但我已经关闭了滚动的能力,UIWebView使用属性self.questionWebView.userInteractionEnabled = NO;.目前使用UIWebView是我显示HTML表格的最佳策略.

Alo*_*ver 16

根据要求改进Rob的答案.

正如Rob已经提到的,UIScrollViews在Auto Layout下有一些特殊的行为.

在这种情况下感兴趣的是scrollView总宽度是通过使用其子视图总宽度来确定的.因此,虽然scrollView已经向webView询问其宽度,但您告诉webView也要求scrollView查询其宽度.这就是为什么它不起作用.一个是问另一个,没有人知道答案.您需要另一个参考视图作为webView的约束,然后scrollView也能够成功询问其预期宽度.

这可以轻松完成:创建另一个视图,containerView并将scrollView作为子视图添加到其中.然后设置适当的约束containerView.假设您希望scrollView以viewController为中心,边缘有一些填充.所以这样做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];
Run Code Online (Sandbox Code Playgroud)

然后,您可以继续将webView作为子视图添加到scrollView并设置其宽度:

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

[self.view addConstraint:makeWidthTheSameAsScrollView];
Run Code Online (Sandbox Code Playgroud)

这将使scrollview像webView一样大和高,并且它们都将按预期放置(在containerView上设置约束).