##传统写法 曾经我们这样初始化一个常量
let redView: UIView = { let view = UIView() view.backgroundColor = .red view.frame = CGRect(x: 100,y: 100,width: 100,height: 100) return view }()
OC中也有类似的写法.在Swift中,声明一个常量之后接着的闭包中进行初始化,而不是之后在 viewDidLoad 或其他类似的方法中进行设置,这种写法的确也很不错! 但是否认为直接在闭包中使用view这样的命名方式显得太low了. twitter有一篇推文流传甚广.
他参照了一个gist
仿照上面的写法,在闭包中使用$0,执行时传入一个用来初始化的UIView
使用$0
let greenView: UIView = { $0.backgroundColor = .green $0.frame = CGRect(x: 100,y: 200,height: 100) return $0 }(UIView()) self.view.addSubview(greenView)
在推文评论中有哥们推荐了一个日本小伙子封装的库,瞬间感觉好NB
import Foundation import CoreGraphics public protocol Then {} extension Then where Self: Any { /// Makes it available to set properties with closures just after initializing and copying the value types. /// /// let frame = CGRect().with { /// $0.origin.x = 10 /// $0.size.width = 100 /// } public func with(_ block: (inout Self) -> Void) -> Self { var copy = self block(©) return copy } /// Makes it available to execute something with closures. /// /// UserDefaults.standard.do { /// $0.set("devxoul",forKey: "username") /// $0.set("devxoul@gmail.com",forKey: "email") /// $0.synchronize() /// } public func `do`(_ block: (Self) -> Void) { block(self) } } extension Then where Self: AnyObject { /// Makes it available to set properties with closures just after initializing. /// /// let label = UILabel().then { /// $0.textAlignment = .Center /// $0.textColor = UIColor.blackColor() /// $0.text = "Hello,World!" /// } public func then(_ block: (Self) -> Void) -> Self { block(self) return self } } extension NSObject: Then {} extension CGPoint: Then {} extension CGRect: Then {} extension CGSize: Then {} extension CGVector: Then {}
##NB写法 例如
let label = UILabel().then { $0.frame = CGRect(x: 100,y: 300,height: 100) $0.text = "测试" $0.backgroundColor = .purple $0.textAlignment = .center $0.font = UIFont.systemFont(ofSize: 19) } self.view.addSubview(label)
三种方法同样可以做到初始化一个常量 不是你认为哪种更加酷呢哈哈哈
原文链接:https://www.f2er.com/swift/322534.html欢迎打赏 点赞,收藏,关注博主 iOS技术交流群 482478166