xcode 如何以编程方式向以编程方式创建的 UIView 添加约束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12795457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add constraints programmatically to a programmatically created UIView?
提问by Jesse Head
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. 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.
但是,约束不适用于视图(至少不是我能看到的)。相反,视图似乎只是从屏幕上消失了。然而,如果约束代码被注释掉,视图将再次加载适当的框架(显然没有应用约束)。当对 Button 或 ImageView 应用相同的约束时,这些约束得到了完美的应用。这让我认为这个问题是因为创建视图时的“initWithFrame”,因为按钮和 ImageView 实际上都不需要指定它的大小。
What are your thoughts? What should I do differently?
你怎么看?我应该怎么做?
采纳答案by Jesse Head
For anyone who comes across this... I needed to add more than one constraint. That did the trick.
对于遇到此问题的任何人......我需要添加多个约束。这就是诀窍。