CoolLayout
CoolLayout 消除了样板代码。让我们创建和排列视图更加简洁和明确。
let circleView = UIView {
$0.backgroundColor = UIColor.red
$0.layer.borderColor = UIColor.black.cgColor
$0.layer.borderWidth = 3
}
self.view.addSubview(circleView)
circleView.activate {
$0.centerXAnchor == self.view.centerXAnchor + 0
$0.centerYAnchor == self.view.centerYAnchor + 0
$0.widthAnchor == 100
$0.heightAnchor == 100
}
circleView.layoutIfNeeded()
circleView.apply {
$0.layer.cornerRadius = $0.frame.width / 2
$0.clipsToBounds = true
}
初始化器
用装饰闭包创建一个视图。(在这种情况下,视图的 translatesAutoresizingMaskIntoConstraints 标志被设置为 false。)
您还可以重用视图的装饰逻辑。
enum Deco {
enum Label {
static let headLine: (UILabel) -> Void = {
$0.textColor = UIColor.black
$0.font = UIFont.boldSystemFont(ofSize: 30)
}
static let centerAlgin: (UILabel) -> Void = {
$0.textAlignment = .center
}
}
enum View {
static let yellowWithDarkBorder: (UIView) -> Void = {
$0.backgroundColor = UIColor.yellow
$0.layer.borderColor = UIColor.black.cgColor
$0.layer.borderWidth = 2
}
}
}
...
let label1 = UILabel.build {
Deco.Label.headLine,
Deco.Label.centerAlgin
}
let label2 = UILabel(autoLayout: [
Deco.Label.headLine,
Deco.Label.centerAlgin
])
self.view.addSubview(label)
self.view.addSubview(label2)
还可以使用初始化闭包使用事初始化 UIViewController。这可以非常容易地注入依赖项。
let nextViewController = TableEmbedViewController {
let items = (0..<10).map{ $0 }
$0.viewModel = ViewModel(cellColor: UIColor.red, items: items)
}
应用
在创建视图后,您可以以相同的方式将装饰逻辑应用到视图上。
let label = UILabel {
$0.numberOfLines = 1
$0.text = "row: \(value)"
}
.apply {
Deco.Label.headLine
Deco.Label.centerAlgin
}
// .apply([
// Deco.Label.headLine,
// Deco.Label.centerAlgin
// ])
.apply(Deco.View.yellowWithDarkBorder)
NSLayoutConstraint
以更易读的方式应用并激活 NSLayoutConstraint。
label.activate {
$0.centerXAnchor == self.centerXAnchor + 0
$0.leadingAnchor >= self.leadingAnchor + 20
$0.trailingAnchor <= self.trailingAnchor + -20
$0.topAnchor == self.topAnchor + 30
$0.bottomAnchor == self.bottomAnchor + -30
}
您还可以使用常规函数表达式创建 NSLayoutConstraint。
self.label.apply {
$0.text = "This method builds faster than using a custom operator."
}
.activate {
$0.centerXAnchor.equal(self.view.centerXAnchor)
$0.topAnchor.equal(self.circleView.bottomAnchor + 50)
$0.leadingAnchor.greaterThan(orEqual: self.view.leadingAnchor + 20)
$0.trailingAnchor.lessThan(orEqual: self.view.trailingAnchor + -20)
}
要求
- iOS 9.0
- Swift 5.0
安装
CocoaPods
pod 'CoolLayout', '1.2.0'
Carthage
github "gearmamn06/CoolLayout" "1.2.0"
Swift 包管理器
dependencies: [
.package(url: "https://github.com/gearmamn06/CoolLayout.git", from: "1.2.0")
]
贡献者
wade.hawk, riley.kang