A lightweight DSL for simple auto layout in Swift.
使用
ClosureLayout允许您通过将简化的闭包传递给名为layout
的函数来创建和激活约束。ClosureLayout确保调用translatesAutoresizingMaskIntoConstraints = false
,因此您可以省略那一行。在布局闭包中使用简单的运算符,您可以定义如下约束:
label.layout {
$0.top == view.topAnchor + 30
$0.leading == view.leadingAnchor + 20
$0.size == CGSize(width: 200, height: 40)
}
button.layout {
$0.width == otherView.widthAnchor - 40
$0.height == otherView.heightAnchor + 10
$0.centerX == otherView.centerXAnchor
$0.centerY == otherView.centerYAnchor
}
而不是编写这个
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 30),
label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
label.widthAnchor.constraint(equalToConstant: 200),
label.heightAnchor.constraint(equalToConstant: 40)
])
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.widthAnchor.constraint(equalTo: otherView.widthAnchor, constant: -40),
button.heightAnchor.constraint(equalTo: otherView.heightAnchor, constant: 10),
button.centerXAnchor.constraint(equalTo: otherView.centerXAnchor),
button.centerYAnchor.constraint(equalTo: otherView.centerYAnchor)
])
此外,该库提供了一个定义样板约束的便捷方法。在使用自动布局时,您通常需要将子视图的每个边缘都约束到其父视图上。您可能会为表格头中的一个标签创建一个包装器或用模糊效果填充一个透明视图等。在这些情况下,您可以使用一种<强>单一的方法来创建所需的约束
wrapper.fillWith(subview)
等同于
wrapper.addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
subview.topAnchor.constraint(equalTo: wrapper.topAnchor).isActive = true
subview.bottomAnchor.constraint(equalTo: wrapper.bottomAnchor).isActive = true
subview.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor).isActive = true
subview.trailingAnchor.constraint(equalTo: wrapper.trailingAnchor).isActive = true
您可以为此函数提供间距,这将设置相应的约束上的给定常量
let insets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
wrapper.fillWith(subview, insets: insets)
如果您需要某个约束的引用,您可以从函数返回的元组中获取它们。
let constraints = wrapper.fillWith(subview)
self.subviewTopConstraint = constraints.top
安装
ClosureLayout可以通过CocoaPods获取。要安装它,只需将以下行添加到Podfile中:
pod 'ClosureLayout'
致谢
ClosureLayout基于一篇文章编写,由John Sundell编写。收听他的播客并在网站上查看更多关于Swift开发的精彩内容。
许可证
ClosureLayout开源许可协议为MIT。详细信息请查看LICENSE文件。