使用 NSLayoutConstraint 实例化和设置 UIButton 子类的大小

Posted

技术标签:

【中文标题】使用 NSLayoutConstraint 实例化和设置 UIButton 子类的大小【英文标题】:Instantiating and setting size of a UIButton subclass with NSLayoutConstraint 【发布时间】:2012-10-05 18:59:36 【问题描述】:

如何在实例化UIButton 时设置它的大小,以供NSLayoutConstraint 使用?

代码:

UIButtonRaisedSilver *loginButton = [UIButtonRaisedSilver buttonWithType:UIButtonTypeCustom];
[loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
[loginButton setTitle:@"Log in" forState:UIControlStateNormal];

NSDictionary *views = @@"tableView" : self.tableView, @"loginButton": loginButton, @"signupButton": signupButton;

[NSLayoutConstraint constraintsWithVisualFormat:@"V:[tableView]-50-[loginButton()]"
                                        options:NSLayoutFormatAlignAllCenterX
                                        metrics:nil
                                          views:views];

【问题讨论】:

【参考方案1】:

事实证明,宽度和高度也是 ios6/(OSX 10.8) 中约束系统的一部分(我认为它的 10.8 - 还没有为 Mac OS 开发)。

确保高度的约束是垂直的,并在括号中设置高度,如下所示...

例如:

[NSLayoutConstraint constraintsWithVisualFormat:@"V:[loginButton(30)]"
                                    options:NSLayoutFormatAlignAllCenterX
                                    metrics:nil
                                      views:views];

【讨论】:

以上是关于使用 NSLayoutConstraint 实例化和设置 UIButton 子类的大小的主要内容,如果未能解决你的问题,请参考以下文章