简体   繁体   English

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

[英]How to add constraints programmatically to a programmatically created UIView?

I have created a UIView using the following code within viewDidLoad (where 'secondview' obviously is the name of the UIView): 我在viewDidLoad中使用以下代码创建了一个UIView(其中'secondview'显然是UIView的名称):

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

Then within viewDidAppear I added constraints to this view: 然后在viewDidAppear中我向此视图添加了约束:

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

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. 将相同的约束应用于Button或ImageView时,约束将完美应用。 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. 这让我认为问题是因为创建View时'initWithFrame',因为按钮和ImageView实际上都不需要指定它的大小。

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. 这就是诀窍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM