[英]Matching subview's width to it's superview using 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
)的宽度时,当应用自动布局约束时,它的宽度不会改变。
问题
ps我知道这是违反Apple的建议将UIWebView
放在UIScrollView
,但是我已经关闭了使用属性self.questionWebView.userInteractionEnabled = NO;
滚动UIWebView
功能self.questionWebView.userInteractionEnabled = NO;
。 目前使用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上设置约束)。
Scrollviews在与自动布局的交互方式上有点奇怪。 请参阅TN2154 (UIScrollView和Autolayout)。
另请参见UIScrollView不使用自动布局约束 。
通常,您需要以“滚动视图的当前宽度”之外的其他方式获取包含视图的宽度,因为在自动布局中,scrollview的宽度(即内容宽度)是根据其内容定义的。 因此,您当前的请求是循环的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.