【发布时间】:2016-11-23 05:21:43
【问题描述】:
我想添加一个按钮作为根视图的子视图。按钮必须水平放置在中心以及垂直放置在超级视图的中心。我以编程方式使用NSLayoutConstraints。这是我的代码。
class ViewController: UIViewController {
var button: UIButton!
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
button = UIButton()
button.setTitle("Hello World", forState: .Normal)
button.backgroundColor = UIColor.blueColor()
button.sizeToFit()
self.view.addSubview(button)
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: button, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0)
])
}
}
我收到以下警告消息,但我也没有得到想要的结果。
2016-07-20 11:01:10.187 build[26982:309535] 无法同时 满足约束。可能至少有一个约束条件 以下列表是您不想要的。
试试这个:
(1) 查看每个约束并尝试找出你没有 预计;
(2) 找到添加了不需要的约束的代码 并修复它。 (注:如果你看到 NSAutoresizingMaskLayoutConstraints 你不明白的,参考 到 UIView 属性的文档 translatesAutoresizingMaskIntoConstraints) ( "", "", " (名称: '|':UIViewControllerWrapperView:0x7faa4be31770 )>", "")
将尝试通过打破约束来恢复
在 UIViewAlertForUnsatisfiableConstraints 创建一个符号断点 在调试器中捕获它。中的方法 UIView 上的 UIConstraintBasedLayoutDebugging 类别列于 也可能有帮助。 2016-07-20 11:01:10.188 build[26982:309535] 无法同时满足约束。 以下列表中的至少一个约束可能是一个 你不想要。
试试这个:(1)查看每个约束并尝试找出哪个约束 你没想到;
(2) 找到添加了不需要的约束的代码 并修复它。 (注:如果你看到 NSAutoresizingMaskLayoutConstraints 你不明白的,参考 到 UIView 属性的文档 translatesAutoresizingMaskIntoConstraints) ( "", "", "", " (名称:'|':UIViewControllerWrapperView:0x7faa4be31770)>")
将尝试通过打破约束来恢复
在 UIViewAlertForUnsatisfiableConstraints 创建一个符号断点 在调试器中捕获它。中的方法 UIView 上的 UIConstraintBasedLayoutDebugging 类别列于 也可能有帮助。
【问题讨论】:
标签: ios nslayoutconstraint programmatically-created