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

前端之家收集整理的这篇文章主要介绍了ios – 使用autolayout将子视图的宽度与其超级视图相匹配前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目标:

有一个UIWebView的宽度与它的superview相同,这是一个使用autolayout约束的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);

当前结果

当我记录self.questionWebView(UIWebView)的宽度时,应用自动布局约束的宽度不会改变.

问题

这是正确的方法吗?
>我做错了什么?

p.s我知道这是针对苹果的建议,将UIWebView放在UIScrollView中,但是我已经关闭使用属性self.questionWebView.userInteractionEnabled = NO ;.滚动UIWebView的功能.目前使用的UIWebView是显示HTML表格的最佳策略.

解决方法

根据要求改进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];

然后,您可以继续将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];

这将使scrollview与webView一样大而高,并且它们都将按照意图放置(在containerView上设置约束).

原文链接:https://www.f2er.com/iOS/329379.html

猜你在找的iOS相关文章