<分区>
我是 iOS 开发新手。我想在没有 Storyboard或 xib/nib 的情况下构建布局。所以我试图以编程方式添加约束。 我搜索了一些关于以编程方式添加约束的教程。但是 View 无法正确显示。
我正在我的 ViewController 类中尝试这段代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let testView = UIView()
self.view.addSubview(testView)
// Add Constraints
self.view.translatesAutoresizingMaskIntoConstraints = false
testView.translatesAutoresizingMaskIntoConstraints = false
let top = NSLayoutConstraint(item: testView, attribute: .top, relatedBy: .equal
, toItem: self.view, attribute: .top, multiplier: 1, constant: 50.0)
let bottom = NSLayoutConstraint(item: testView, attribute: .bottom, relatedBy: .equal
, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -50.0)
let leading = NSLayoutConstraint(item: testView, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: self.view, attribute: .leading, multiplier: 1, constant: 50.0)
let trailing = NSLayoutConstraint(item: testView, attribute: .trailing, relatedBy: .greaterThanOrEqual, toItem: self.view, attribute: .trailing, multiplier: 1, constant: -50.0)
self.view.addConstraints([top, bottom, leading, trailing])
}
通常,他们不需要在教程中定义 View 的大小或关于宽度和高度的约束。但是 View 可以显示在他们的教程中。在我的例子中,即使设置了顶部、底部、前导和尾随约束,我的 testView 也无法在应用程序中显示它。我错过了什么吗?有什么问题?
教程之一: http://www.knowstack.com/swift-nslayoutconstraint-programatically-sample-code/
编辑:
让我解释更多。我想创建一个适用于通用设备的 UIView
。 UIView
具有 constant: 10
的顶部、底部、前导和尾随约束。所以,我不需要设置 UIView
的大小。
Expected Result (I am using draw tool to simulate the result)