如果您使用自动布局,请设置translateAutoResizingMaskIntoConstraints
为false
并忽略框架,但不要忘记手动添加约束。
这是一个简单的例子:
override func viewDidLoad() {
super.viewDidLoad()
// no auto layout
let v = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
v.backgroundColor = UIColor.blue
view.addSubview(v)
// with auto layout
let v2 = UIView()
v2.backgroundColor = UIColor.red
// use auto layout
v2.translatesAutoresizingMaskIntoConstraints = false
// add width / height constraints
v2.addConstraint(NSLayoutConstraint(item: v2, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100))
v2.addConstraint(NSLayoutConstraint(item: v2, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100))
// must add to hirarchy before adding the following constraints
view.addSubview(v2)
view.addConstraint(NSLayoutConstraint(item: v2, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 100))
view.addConstraint(NSLayoutConstraint(item: v2, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0))
// auto layout, visual format
let v3 = UIView()
v3.translatesAutoresizingMaskIntoConstraints = false
v3.backgroundColor = UIColor.green
let views = [ "v3" : v3 ]
// must add v3 as subview before adding constraints referencing the parent view
view.addSubview(v3)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-200-[v3(100)]", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[v3(100)]", options: [], metrics: nil, views: views))
}
对于许多视图,不需要指定大小,因为某些视图提供了他们想要的大小intrinsicContentSize
。
您可以将其用于按钮以使它们具有“需要”的大小,或使用约束强制其他大小。
对于自定义视图 - 您可以覆盖此属性以提供您自己的“所需大小”逻辑。