问题描述
我正在使用以下代码向视图添加叠加视图:
I am using the following code to add a overlay view to a view:
UIView *overlayView = [[UIView alloc] init];
overlayView.backgroundColor = [UIColor redColor];
[self.view addSubview:overlayView];
overlayView.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *views = NSDictionaryOfVariableBindings(overlayView);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[overlayView]|" options:0 metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[overlayView]|" options:0 metrics:nil views:views]];
如果我将此代码放在 UIViewController
的 viewDidLoad
方法中,它会正常工作.但是,如果我在 UITableViewController
中做同样的事情,覆盖视图会得到一个零帧.
If I place this code in the viewDidLoad
method of a UIViewController
it works fine. However, if I do the same in a UITableViewController
the overlay view gets a zero frame.
我已经检查了视图,我可以看到约束确实被正确添加并且它们处于活动状态.但出于某种原因,它们似乎被忽略了.
I have inspected the view and I can se the constraints do get added correctly and they are active. But for som reason they seem to be ignored.
我没有收到任何错误或警告.
I don't get any error or warning.
我在这里遗漏了什么?
PS:我知道我可以使用 self.view.bounds
作为框架来实例化叠加视图,并且它可以工作.但是,我需要使用自动布局.
PS: I know I can instantiate the overlay view with self.view.bounds
as frame, and it works. However, I need to use autolayout.
推荐答案
怀疑是因为 UITableView 是一个 UIScrollView 并且自动布局在使用建立自己的边界系统的视图(例如滚动视图或表格)时有一些警告查看).
Suspect it's because the UITableView is a UIScrollView and auto layout has a few caveats when working with views that establish their own bounds systems (such as the scroll view or table view).
在覆盖视图上设置的约束是这样的,它被约束到滚动视图的顶部、右侧、底部和左侧边缘,因此被约束到滚动视图的内容区域而不是滚动视图的框架.
The constraints set on the overlay view are such that it is constrained to the top, right, bottom, and left edges of the scroll view, and thus to the content area of the scroll view rather than the scroll view's frame.
见https://developer.apple.com/library/ios/technotes/tn2154/_index.html和 自动布局指南:使用滚动视图:
滚动视图的边缘或边距之间的约束和它的内容附加到滚动视图的内容区域.
不是将覆盖视图限制到内容区域,而是将其限制到滚动视图的框架.根据上面的参考资料,这可以通过将覆盖视图的宽度/高度限制为滚动视图来完成,或者通过将覆盖视图限制为滚动视图之外的视图来完成.
Instead of constraining overlay view to the content area, constrain it to the scroll view's frame instead. According to the above references, this can be done either by constraining overlay view's width/height to the scroll view, or by constraining the overlay view to a view outside of the scroll view.
这篇关于使用自动布局向 UITableView 添加子视图不会设置其框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!