【发布时间】:2019-02-06 06:31:36
【问题描述】:
我有一个有趣的问题。我的应用程序完全通过代码而不是故事板进行管理。我有一个以编程方式呈现的 UIViewController。它为它创建一个按钮和约束。
这就是控制器代码的样子。
import Foundation
import UIKit
class CreateViewController: UIViewController {
lazy var button: UIButton = {
let button = UIButton()
button.layer.bounds = CGRect(x: 0, y: 0, width: 50, height: 50)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .green
return button
}()
func setupViews() {
self.view.addSubview(button)
}
func setupConstraints() {
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[button]-100-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["button": button]))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[button(50)]-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["button": button]))
}
override func viewDidLoad() {
setupViews()
setupConstraints()
}
}
它会抛出这个错误。
(
"<NSLayoutConstraint:0x60000288bb60 UIButton:0x7fa1ab422680.leading == UILayoutGuide:0x6000032da760'UIViewLayoutMarginsGuide'.leading NSSpace(0) (active)>",
"<NSLayoutConstraint:0x60000288bb10 UIButton:0x7fa1ab422680.width == 50 (active)>",
"<NSLayoutConstraint:0x60000288d7c0 UILayoutGuide:0x6000032da760'UIViewLayoutMarginsGuide'.trailing == UIButton:0x7fa1ab422680.trailing NSSpace(0) (active)>",
"<NSLayoutConstraint:0x6000028fe990 'UIView-Encapsulated-Layout-Width' UIView:0x7fa1ab4224a0.width == 375 (active)>",
"<NSLayoutConstraint:0x60000288fe30 'UIView-leftMargin-guide-constraint' H:|-(16)-[UILayoutGuide:0x6000032da760'UIViewLayoutMarginsGuide'](LTR) (active, names: '|':UIView:0x7fa1ab4224a0 )>",
"<NSLayoutConstraint:0x60000288d180 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x6000032da760'UIViewLayoutMarginsGuide']-(16)-|(LTR) (active, names: '|':UIView:0x7fa1ab4224a0 )>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60000288d7c0 UILayoutGuide:0x6000032da760'UIViewLayoutMarginsGuide'.trailing == UIButton:0x7fa1ab422680.trailing NSSpace(0) (active)>
我的目标很简单。我希望按钮在底部上方 100 像素处,水平居中,并具有固定的宽度和高度。
这就是控制器被实例化的方式。它存在于
let nav2 = UINavigationController()
let create = CreateViewController()
nav2.viewControllers = [create]
nav2.navigationBar.isTranslucent = false
...
let tabs = UITabBarController()
tabs.viewControllers = [..., nav2, ...]
tabs.delegate = self
任何帮助理解为什么会违反这些约束将不胜感激!如果问题的任何部分不清楚,请告诉我。
仅供参考,结果视图如下所示:
【问题讨论】:
标签: ios swift autolayout nslayoutconstraint ios-autolayout