TinyConstraints 是使 Auto Layout 更易于人使用的语法糖。
translatesAutoresizingMaskIntoConstraints
,因为 TinyConstraints
会为您完成。使用 NSLayoutConstraint
将视图附加到其父视图
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: superview.topAnchor, constant: 0),
view.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: 0),
view.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: 0),
view.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: 0)
])
使用 TinyConstraints
view.edgesToSuperview()
或
view.edgesToSuperview(insets: .top(10) + .left(10))
使用 NSLayoutConstraint
约束视图的中心到其父视图
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: superview.centerXAnchor, constant: 0)
view.centerYAnchor.constraint(equalTo: superview.centerYAnchor, constant: 0)
])
使用 TinyConstraints
view.center(in: superview)
或
view.center(in: superview, offset: CGPoint(x: 10, y: 10))
TinyConstraints
为您提供方便且精简的类型别名来处理约束。
Constraint
= NSLayoutConstraint
Constraints
= [NSLayoutConstraint]
这约束视图的 top-anchor
到父视图的 top-anchor
view.top(to: superview)
这约束 firstView
的 top-anchor
到 secondView
的 bottom-anchor
firstView.topToBottom(of: secondView)
通常您需要将视图约束到其父视图,使用 TinyConstraints 您可以非常轻松地做到这一点
view.edgesToSuperview()
或仅一个边缘
view.topToSuperview()
或者您可以附加除一个以外的所有边缘,像这样
view.edgesToSuperview(excluding: .bottom)
对于几乎所有约束,您都可以设置 relation
和 priority
属性。默认关系是 .equal
,默认优先级是 .required
container.width(150, relation: .equalOrLess, priority: .high)
这里我们创建一组非激活约束并将它们存储到我们的属性中
let constraints = view.size(CGSize(width: 100, height: 100), isActive: false)
除了默认的 NSLayoutConstraint
激活外,TinyConstraints
还提供了一种激活一组约束的方法
constraints.activate()
您也可以在动画中执行此操作
oldConstraints.deActivate()
constraints.activate()
UIViewPropertyAnimator(duration: 1, dampingRatio: 0.4) {
self.layoutIfNeeded()
}.startAnimation()
这里我们向视图添加高度约束,存储它并在以后对其进行动画处理
let height = view.height(100)
height.constant = 200
UIViewPropertyAnimator(duration: 1, dampingRatio: 0.4) {
self.layoutIfNeeded()
}.startAnimation()
堆栈提供了一种在父视图中将视图组合在一起约束的方法
let views = [logo, title, description]
superview.stack(views, axis: .vertical, spacing: 10)
TinyConstraints 可通过 CocoaPods 获得。要安装它,只需将以下行添加到您的 Podfile
pod "TinyConstraints"
TinyConstraints 可通过 Carthage 获得。要安装它,只需将以下行添加到您的 Cartfile
github "roberthein/TinyConstraints"
TinyConstraints 可通过 Swift Package Manager 获得。要安装它,在 Xcode 11.0 或更高版本中,选择 File
> Swift Packages
> Add Package Dependency...
并添加 TinyConstraints 存储库 URL
https://github.com/roberthein/TinyConstraints.git
请随意创建 pull request,打开 issue 或在 Twitter 上找到我。