我是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。在詢問之前,你是否已經檢查過所有類似的問題?像這樣的例子有大量的答案和解釋:http://stackoverflow.com/questions/26180822/swift-adding-constraints-programmatically – 2017-02-18 16:54:13
我之前檢查過這個問題。 UIView的大小已被定義爲寬度:100,高度:100在最高速率的答案。我更新了我的問題。請檢查,謝謝。 – kk777
嘗試在添加約束後添加view.layoutIfNeeded,如果沒有其他解決方案適用於您或此處有多個答案。 – 2017-02-19 07:31:25