你可以做这样的事情,
let content = UIView()
content.backgroundColor = UIColor.redColor()
content.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(content)
let topConstraint = NSLayoutConstraint(item: content, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
view.addConstraint(topConstraint)
let leadingConstraint = NSLayoutConstraint(item: content, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
view.addConstraint(leadingConstraint)
let bottomConstraint = NSLayoutConstraint(item: content, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
view.addConstraint(bottomConstraint)
let trailingConstraint = NSLayoutConstraint(item: content, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
view.addConstraint(trailingConstraint)
let heightConstraint = NSLayoutConstraint(item: content, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
view.addConstraint(heightConstraint)
在这里,你应该考虑holder
而不是view
。
这种约束是中间视图。对于第一和最后一个视图的场景应该是不同的东西一样,
//Top constraint for first view should be like,
let topConstraintForfirstView = NSLayoutConstraint(item: content, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
view.addConstraint(topConstraintForfirstView)
//Bottom constraint for last view should be like,
let bottomConstraintForLastview = NSLayoutConstraint(item: content, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
view.addConstraint(bottomConstraintForLastview)
你可以通过改变约束constant
管理空间或距离。如果你想要20像素之间的垂直间距视图然后你的常数top constraints should be 20
。
你可以参考this answer作为参考。
不要给高度和底部。如果你给定高度,那么你不需要底部,如果你给底部,那么你不需要固定高度。
希望这将有助于:)
你有什么理由宁愿手动布局'NSStackView'? –