SwiftConstraints
NSLayoutConstraint 的 Swift 映射。
安装
Cocoapods
pod 'SwiftConstraints', '~> 1.0.1'
用法
在视图的子视图之间添加约束
// align the subview 10 points from the left of the superview
superview.addConstraint(toItem: subview, attribute: .leading, constant: 10)
// align the subview 20 points or less from the vertical center of the superview
superview.addConstraint(toItem: subview, attribute: .centerY, relatedBy: .lessThanOrEqual, constant: 20)
向视图添加约束以填充
// subview completely fill the superview
superview.addConstraints(fillView: subview)
// subview fill the superview with 20 points of padding
superview.addConstraints(fillView: subview, constant: 20)
向视图的两个子视图添加约束
// align the left sides of two view by 10 points
superview.addConstraint(withItems: viewOne, andItem: viewTwo, attribute: .left, constant: 10)
// align the first baseline of two labels
superview.addConstraint(withItems: labelOne, andItem: labelTwo, attribute: .firstBaseline)
在视图的两个子视图之间添加约束
// sit two views next to each other horizontally
superview.addConstraint(betweenItems: viewOne, toItem: viewTwo, axis: .horizontal)
// put the second view underneath the first view by 15 points
superview.addConstraint(betweenItems: viewOne, toItem: viewTwo, axis: .vertical, constant: 15)
向视图本身添加约束
// set the view width to 120 points
superview.addConstraint(toSelf: .width, constant: 120)
// set the aspect ratio of the view to 16:9 or greater
superview.addConstraint(toSelf: .width, toAttribute: .height, multiplier: 16/9.0, constant: 0)
向子视图添加约束以提供相同的尺寸
// Set views to the same height
superview.addConstraints(equalDimensions: [viewOne, viewTwo, viewThreee, viewFour], axis: .vertical)
向子视图添加约束以对齐
// Align views to the horizontal center of the view
superview.addConstraints(alignItems: [viewOne, viewTwo, viewThreee, viewFour], attribute: .centerX)
添加空间子视图约束
// evenly space views horizontally with 20 points of padding in a superview
superview.addConstraints(equallySpaced: [viewOne, viewTwo, viewThreee, viewFour], axis: .horizontal, constant: 20)