使用自动布局将子视图的宽度匹配到超级视图
目标:
有一个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);
当前结果
当我loggingself.questionWebView
( UIWebView
)的宽度时,它的宽度在应用自动布局约束时不会改变。
问题
- 这是正确的方法吗?
- 我究竟做错了什么?
PS我知道这是违反苹果的build议将UIWebView
放在UIScrollView
,但是我已经closures了使用属性self.questionWebView.userInteractionEnabled = NO;
滚动UIWebView
的能力self.questionWebView.userInteractionEnabled = NO;
。 而目前使用UIWebView是我最好的策略来显示HTML表格。
根据要求改进Rob的答案。
正如Rob已经提到的, UIScrollViews
在自动布局下有特殊的行为。
在这种情况下感兴趣的是scrollView总宽度是通过使用其子视图总宽度来确定的。 所以,虽然scrollView已经问webView的宽度,你告诉webView也要求scrollView的宽度。 这就是为什么它不起作用。 一个人问另一个人,没有人知道答案。 你需要另一个引用视图作为webView的约束条件,然后scrollView也能够成功地询问它的预期宽度。
一个简单的方法可以这样做:创build另一个视图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的当前宽度”之外,还需要获取包含视图的宽度,因为在自动布局中,scrollview的宽度(即内容宽度)是根据其内容定义的。 因此,您目前的要求是循环的。