斯威夫特版本
更新了斯威夫特3
這個例子將顯示兩種方法以編程方式添加下列約束一樣,如果做它在界面生成器中:
寬度和高度
中心集裝箱
樣板代碼
override func viewDidLoad() {
super.viewDidLoad()
// set up the view
let myView = UIView()
myView.backgroundColor = UIColor.blue
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
// Add constraints code here (choose one of the methods below)
// ...
}
方法1:錨式
// width and height
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true
// center in container
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
方法2:NSLayoutConstraint樣式
// width and height
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true
// center in container
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true
注
在上面的代碼中,vivi是什麼? – iDev
請將標題改爲「iOS」而不是「IOS」 - 後者是指Cisco的交換機/路由器操作系統。使我困惑。謝謝。 – armani
關於這方面的幾個問題:(1)當它「不滿足某些約束條件」時,你會得到什麼錯誤? (2)你是否正在將自動調整大小轉換爲'myView'上的約束? (3)什麼是'vivi'(如ACB問)? (4)你有'myView'屬性在'self'聲明嗎? – Tim