如何以编程方式将约束添加到以编程方式创建的UIView?

问题描述:

我在viewDidLoad中使用以下代码创建了一个UIView(其中'secondview'显然是UIView的名称):

I have created a UIView using the following code within viewDidLoad (where 'secondview' obviously is the name of the UIView):

secondview = [[UIView alloc] initWithFrame:self.view.frame];
    [secondview setBackgroundColor: [UIColor yellowColor]];
    secondview.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:secondview];

然后在viewDidAppear中我为此视图添加了约束:

Then within viewDidAppear I added constraints to this view:

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:secondview attribute:NSLayoutAttributeRight
    relatedBy:NSLayoutRelationEqual
    toItem:self.view
    attribute:NSLayoutAttributeRight
    multiplier:1.0f constant:-20.0f];
[self.view addConstraint:constraint];

但是,约束不会应用于视图(至少不是我能看到的)。相反,视图似乎只是从屏幕上消失了。但是,如果约束代码被注释掉,则视图再次加载适当的帧(显然没有应用约束)。将相同的约束应用于Button或ImageView时,约束将完美应用。这让我认为问题是因为创建View时'initWithFrame',因为按钮和ImageView实际上都不需要指定它的大小。

However, the constraints are not applied to the view (atleast not that I can see). Instead, the view simply seems to disappear from the screen. If the constraint code is commented out however, the view once again loads with the appropriate frame (obviously without the constraints being applied). When applying the same constraints to a Button or ImageView, the constraints are applied perfectly. This has lead me to think that the issue is because of 'initWithFrame' when creating the View, as neither the button nor ImageView actually require it's size to be specified.

什么你的想法?我应该做些什么?

What are your thoughts? What should I do differently?

对于遇到此问题的任何人......我需要添加多个约束。这就行了。

For anyone who comes across this... I needed to add more than one constraint. That did the trick.