如何添加约束编程到一个程序创建的UIView? [英] How to add constraints programatically to a programatically created UIView?

查看:120
本文介绍了如何添加约束编程到一个程序创建的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应用相同的约束时,约束被完美地应用。这导致我认为问题是因为'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.

这篇关于如何添加约束编程到一个程序创建的UIView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆