繁体   English   中英

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

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

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

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

然后在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];

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

你怎么看? 我该怎么办?

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

暂无
暂无

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

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