在手寫程式碼的時候,常常會用到一些懶載入的方式來書寫控制元件,下面是個Then協議,不會產生迴圈引用的問題,程式碼看起來比較的緊湊,更加的直觀。
public protocol Then {}
extension Then where Self: AnyObject {
public func then( block: (Self) -> Void) -> Self {
block(self)
return self
}
/*
let _ = UILabel().then { (label) in
label.backgroundColor = .blue
label.font = UIFont.systemFont(ofSize: 18)
label.textAlignment = .center
label.text = "Then協議庫"
label.frame = CGRect.init(x: 20, y: 200, width: 150, height: 40)
view.addSubview(label)
}
*/
/*
// 2.1 (推薦)無引數,無需命名,用$取引數,可自動聯想屬性
let lable = UILabel().then {
$0.backgroundColor = .blue
$0.font = UIFont.systemFont(ofSize: 18)
$0.textAlignment = .center
$0.text = "Then庫寫法_2.1"
$0.frame = CGRect.init(x: 200, y: 260, width: 150, height: 40)
view.addSubview($0)
}
lable.backgroundColor = UIColor.red
*/
}
extension UIView: Then {}
複製程式碼