代码见下方
//不自动转换为constrains
//历史原因造成的
//得设成false后下面添加的约谁才能生效
subView.translatesAutoresizingMaskIntoConstraints =false
//添加视图进去
view.addSubview(subView)
//创建三条约束
letsc1 = NSLayoutConstraint(
item: subView,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: topLayoutGuide,
attribute: NSLayoutAttribute.Bottom,
multiplier:1,
constant:0
)
letsc2 = NSLayoutConstraint(
item: subView,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: subView.superview,
attribute: NSLayoutAttribute.Leading,
multiplier:1,
constant:0
)
letsc3 = NSLayoutConstraint(
item: subView,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: subView.superview,
attribute: NSLayoutAttribute.Trailing,
multiplier:1,
constant:0
)
//使创建的约束生效
NSLayoutConstraint.activateConstraints([sc1,sc2,sc3])