3
我想添加一些約束的子視圖。添加約束子視圖不起作用
但我的看法沒有出現。 下面是一些代碼,有誰知道哪裏出了問題?
(如果我添加的UITextField例如它工作正常...)
class TestViewController:UIViewController {
override func viewDidLoad() {
//Do not work...
addAndLayout(v: UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)))
//Works fine
//addAndLayout(v: UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0)))
}
func addAndLayout(v:UIView) {
v.backgroundColor = UIColor.red
view.addSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
let leading = NSLayoutConstraint(item: v, attribute: .leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
let trailing = NSLayoutConstraint(item: v, attribute: .trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: v, attribute: .top, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)
view.addConstraints([leading, trailing, top])
}
}
沒問題,自動佈局並不是最舒服的方法之一。 –