Swift 2.0 になって、protocol extensionが使えるようになりました。
これを使えば、例えば一つのアプリの中でUIVIew, UIButtonなどに共通のデザインを組み合わせて使い回すようなことが出来るのではないかと考えました。
試しに以下の様なコードをPlaygroundで書いてみました。
自分は以下のコードのようなコードは
- 「プロトコルを書いた時点でデザインに要求される要素(text, imageなど)が決まる」
- 「デザインの差し替えが楽」
かと思って書いてみましたがどうなのでしょうか。また、as! でキャストしているところが些か気持ち悪く感じますが良い方法はあるでしょうか。
- 「protocol extensionを使うにしても、もっと賢く出来る」
- 「そもそもprotocol extensionを使う必要がない」
などの意見があればお聞かせ願いたいです。
Swift
1 2//: Playground - noun: a place where people can play 3 4import UIKit 5 6// MARK: - Background Protocol - 7protocol BGProtocol { 8 func background() 9} 10 11protocol BGNone : BGProtocol {} 12extension BGNone { 13 func background() { 14 (self as! UIView).backgroundColor = UIColor.clearColor() 15 (self as! UIView).layer.borderColor = UIColor.clearColor().CGColor 16 } 17} 18 19protocol BGModesty : BGProtocol {} 20extension BGModesty { 21 func background() { 22 (self as! UIView).backgroundColor = UIColor.blueColor() 23 } 24} 25 26// MARK: - Sound Effect Protocol - 27protocol SETapProtocol { 28 func soundTap() 29} 30 31protocol SETapNone : SETapProtocol {} 32extension SETapNone { 33 func soundTap() {} 34} 35 36protocol SETapClick : SETapProtocol {} 37extension SETapClick { 38 func soundTap() { 39 print("Clicking sound!!") 40 } 41} 42 43// MARK: - Button Protocol - 44protocol ButtonProtocol { 45 func title() 46} 47 48protocol ButtonLabel { 49 var text: String { get } 50} 51extension ButtonLabel { 52 func title() { 53 (self as! UIButton).setTitle(text, forState: .Normal) 54 } 55} 56 57protocol ButtonImage { 58 var image: UIImage { get } 59} 60extension ButtonImage { 61 func title() { 62 (self as! UIButton).setImage(image, forState: .Normal) 63 } 64} 65 66protocol BaseButtonProtocol : BGProtocol, SETapProtocol, ButtonProtocol {} 67 68// MARK: - Custom Buttons - 69class MyButton1 : UIButton, BaseButtonProtocol, 70BGModesty, SETapClick, ButtonLabel { 71 var text = "click me!" 72 73 override init(frame: CGRect) { 74 super.init(frame: frame) 75 background() 76 title() 77 addTarget(self, action: "soundTap", forControlEvents: .TouchUpInside) 78 } 79 80 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } 81} 82 83let button1 = MyButton1(frame: CGRectMake(0, 0, 100, 100)) 84 85// ほか別の組み合わせのUIButtonやUIView多数
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/08/26 11:46