解决方案 1:UIStackView
let totalSubviews = 4
let stackView = UIStackView()
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .Horizontal
stackView.distribution = .EqualSpacing
stackView.alignment = .Center
stackView.spacing = 10
stackView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor, constant: 0).active = true
stackView.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor, constant: 0).active = true
stackView.backgroundColor = UIColor.greenColor()
for _ in 0 ..< totalSubviews {
let subview = UIView()
stackView.addArrangedSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
subview.backgroundColor = UIColor.redColor()
subview.heightAnchor.constraintEqualToConstant(50).active = true
subview.widthAnchor.constraintEqualToConstant(50).active = true
}
解决方案 2:自动布局
您通常可以使用 AutoLayout 来做到这一点。
totalSubviews = 4
totalSubviews = 5
代码
let totalSubviews = 4
let spacing = CGFloat(20)
var subviews = [UIView]()
var previousSubview: UIView?
for i in 0 ..< totalSubviews {
let subview = UIView()
subviews.append(subview)
view.addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
subview.backgroundColor = UIColor.redColor()
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: spacing))
if i == 0 {
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: spacing))
}
else if i < totalSubviews {
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Left, relatedBy: .Equal, toItem: previousSubview, attribute: .Right, multiplier: 1, constant: spacing))
}
if i == totalSubviews - 1 {
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: -spacing))
}
if i != 0 {
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Width, relatedBy: .Equal, toItem: previousSubview!, attribute: .Width, multiplier: 1, constant: 0))
}
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 0, constant: 100))
previousSubview = subview
}