Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gamako/84ec986f85fd26ceccae1b92c6df2f29 to your computer and use it in GitHub Desktop.
Save gamako/84ec986f85fd26ceccae1b92c6df2f29 to your computer and use it in GitHub Desktop.
closureでUIViewの初期化処理をあたえられるための拡張
import UIKit
/**
closureでUIViewの初期化処理をあたえられるための拡張
@noescapeをつけているのでclosureの中でselfをつける必要はない
ex.)
```
override func viewDidLoad() {
let someView = UIView() {
$0.backgroundColor = UIColor().blackColor
view.addSubview(%0)
}
}
```
*/
protocol NoescapeClosureInitialzable : class {
}
extension UIView : NoescapeClosureInitialzable {}
extension NoescapeClosureInitialzable where Self : UIView {
init(@noescape _ initializer: (view : Self) -> ()) {
self.init()
initializer(view: self)
}
init(frame: CGRect, @noescape _ initializer: (view : Self) -> ()) {
self.init(frame: frame)
initializer(view: self)
}
}
extension NoescapeClosureInitialzable where Self : UIButton {
init(type: UIButtonType, @noescape _ initializer: (view : Self) -> ()) {
self.init(type: type)
initializer(view: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment