TinyConstraints 是使 Auto Layout 更易于人使用的语法糖。

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 为您提供方便且精简的类型别名来处理约束。

相等和不等锚点

这约束视图的 top-anchor 到父视图的 top-anchor

view.top(to: superview)

这约束 firstViewtop-anchorsecondViewbottom-anchor

firstView.topToBottom(of: secondView)

约束到父视图

通常您需要将视图约束到其父视图,使用 TinyConstraints 您可以非常轻松地做到这一点

view.edgesToSuperview()

或仅一个边缘

view.topToSuperview()

或者您可以附加除一个以外的所有边缘,像这样

view.edgesToSuperview(excluding: .bottom)

关系和优先级

对于几乎所有约束,您都可以设置 relationpriority 属性。默认关系是 .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)
示例项目中查找这些示例和更多内容。

安装

CocoaPods

TinyConstraints 可通过 CocoaPods 获得。要安装它,只需将以下行添加到您的 Podfile

pod "TinyConstraints"

Carthage

TinyConstraints 可通过 Carthage 获得。要安装它,只需将以下行添加到您的 Cartfile

github "roberthein/TinyConstraints"

Swift Package Manager

TinyConstraints 可通过 Swift Package Manager 获得。要安装它,在 Xcode 11.0 或更高版本中,选择 File > Swift Packages > Add Package Dependency... 并添加 TinyConstraints 存储库 URL

https://github.com/roberthein/TinyConstraints.git

教程

这里有一些由 Alex Nagy 制作的视频教程

建议或反馈?

请随意创建 pull request,打开 issue 或在 Twitter 上找到我