【发布时间】:2017-07-08 03:50:30
【问题描述】:
我是 iOS 开发新手。我想构建没有情节提要或 xib/nib 的布局。所以我试图以编程方式添加约束。 我搜索了一些关于以编程方式添加约束的教程。但是视图无法正确显示。
我正在我的 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])
}
一般来说,他们不需要在教程中定义视图的大小或宽度和高度的约束。但是可以在他们的教程中显示视图。就我而言,我的 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)
【问题讨论】:
-
欢迎来到 SO。在提问之前,您是否已经检查了所有类似的问题?像这样有大量答案和解释的例子:stackoverflow.com/questions/26180822/…
-
我之前检查过这个问题。
UIView的大小在最高比率的答案中被定义为宽度:100,高度:100。我已经更新了我的问题。请检查,谢谢。 -
如果其他解决方案都不适合您或此处的多个答案,请尝试在添加约束后添加 view.layoutIfNeeded。
标签: ios swift uiview autolayout nslayoutconstraint