0
我想創建以下結果:編程方式創建約束 - 2盒
由於只有手動創建NSLayoutConstraints。但目前我只有一個藍色框,或者(如果我不添加UIButton)正確的紅色視圖。
let newView = UIView()
newView.backgroundColor = UIColor.redColor()
newView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(newView)
let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
view.addConstraint(verticalConstraint)
let topContraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
view.addConstraint(topContraint)
let bottomContraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
view.addConstraint(bottomContraint)
let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 200)
view.addConstraint(widthConstraint)
let disableButton = UIButton()
disableButton.backgroundColor = UIColor.blueColor()
disableButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(disableButton)
let leadingConstraint = NSLayoutConstraint(item: disableButton, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
view.addConstraint(leadingConstraint)
let topBContraint = NSLayoutConstraint(item: disableButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
view.addConstraint(topBContraint)
let bottomBContraint = NSLayoutConstraint(item: disableButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
view.addConstraint(bottomBContraint)
let trailingConstraint = NSLayoutConstraint(item: disableButton, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: newView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
view.addConstraint(trailingConstraint)
任何人都可以幫我解決什麼是錯的嗎?有什麼區別,我以哪種順序手動創建約束?
你有沒有嘗試設置兩個視圖之間的水平間距? –
我需要嗎?當我用IB創建時,我不會創建水平間距。只有2個視圖,一個固定寬度,第二個應該通過將所有約束(前導,尾隨,頂部,底部)設置爲0來佔用其他空間。 – derdida
然後第二個應該具有等於第一個固定寬度的前導空間 –