Swift Then语法糖使用教程
2021-08-03 本文已影响0人
JianLee
简介
Then是一个Swift初始化库,使用非常简洁和优雅,大大提高代码可阅读性。
开始使用
依赖
pod 'Then'
切换到项目目录,执行
pod install
1.使用Then初始化控件,并设置属性
例1
lazy var label = UILabel().then({
$0.text = "label"
$0.textColor = .blue
})
![](https://img.haomeiwen.com/i5540252/eb49c7124b50ec6f.jpg)
例2
let redView = UIView().then { (make) in
make.backgroundColor = .red
make.frame = CGRect(x: 50, y: 50, width: 100, height: 100)
}
![](https://img.haomeiwen.com/i5540252/5a6bc5bac0d9897f.jpg)
例3
let redBtn = UIButton().then{(make) in
make.setTitle("点我", for: .normal)
make.setTitleColor(.red, for: .normal)
make.backgroundColor = UIColor.yellow
}
![](https://img.haomeiwen.com/i5540252/3bfe6c0e801822bf.jpg)
例4
let blueBtn = UIButton().then(
{
$0.setTitle("点我", for: .normal)
$0.setTitleColor(.blue, for: .normal)
$0.backgroundColor = UIColor.yellow
}
)
![](https://img.haomeiwen.com/i5540252/f718390d429ed39f.jpg)
添加到视图中展示
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(label)
label.snp.makeConstraints{(make) in
make.width.equalTo(80)
make.height.equalTo(40)
make.center.equalToSuperview()
}
}
2.Then和SnapKit一起使用的方式
override func viewDidLoad() {
super.viewDidLoad()
let blakBtn=UIButton().then(
{
$0.setTitle("点我", for: .normal)
$0.setTitleColor(.white, for: .normal)
$0.backgroundColor = UIColor.black
view.addSubview($0)
$0.snp.makeConstraints{(make) in
make.width.equalTo(80)
make.height.equalTo(40)
make.center.equalToSuperview()
}
})
}
![](https://img.haomeiwen.com/i5540252/4074e8acf09f10d1.jpg)
还有一些其它用法 可以参照官方例子Then