虽然我将subView添加到containerview中。
打印containerView的说明:
<UIView: 0x7fd800b0a1a0; frame = (0 0; 0 0); layer = <CALayer: 0x6040006251e0>
为什么我将视图帧设为(0 0; 0 0)
UIView* containerView = [UIView new];
containerView.translatesAutoresizingMaskIntoConstraints = NO;
[containerView addSubview:contentView];
[containerView addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:|-15-[contentView]-15-|" options:0
metrics:nil views:NSDictionaryOfVariableBindings(contentView)]];
[containerView addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:|[contentView]-15-|" options:0
metrics:nil views:NSDictionaryOfVariableBindings(contentView)]];
答案 0 :(得分:1)
您创建了零帧的视图。使用其他初始值设定项:
UIView *containerView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, w, h)];
但是在将视图添加为子视图后,其框架仍然是错误的。右边的框架将在viewDidLayoutSubviews
之后(对于ViewController)或layoutSubviews
(对于View)
答案 1 :(得分:0)
编辑:
containerView
尚未添加到视图中,在其自身找到像
[self.view addSubview:containerView]
您的问题是您试图将视图(contentView)约束到另一个(containerView)尚未知道它的位置
UIView* containerView = [UIView new];
更改为
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,35)];
总是以编程方式创建视图时,父视图的布局已准备好向其添加子视图并在它们之间挂钩约束
VC启动时,以编程方式创建的约束也只能在viewDidLayoutSubviews
中-(void)viewDidLayoutSubviews
{
if(Once)
{
// Add constraints here
Once = NO
[self.view layoutIfNeeded];
}
}