介绍两个特殊的swift风格的初始化方式,可以让初始化代码更紧凑,更清晰
-
1.懒加载,闭包式写法
fileprivate lazy var closeButton: UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "compose_photo_close"), for: UIControlState.normal) btn.isHidden = true btn.isUserInteractionEnabled = false btn.sizeToFit() return btn }()
-
2.位置参数来初始化
let mySwitch : UISwitch = { view.addSubview($0) CenterViewInSuperview($0, horizontal: true, vertical: true) $0.addTarget(self, action: "action", forControlEvents: .TouchUpInside) return $0 }(UISwitch())