2016-04-23 101 views
0

我想創建UIButton的幾個擴展,所以我可以添加一些功能很容易,只需添加一個協議到自定義按鈕。如果我不需要重寫UIButton中的某些方法,那麼我想我必須對UIButton本身進行擴展。擴展UIButton只有當符合協議

例如,我有幾個協議我的自定義按鈕,可遵循:

protocol CustomLayer { } 

protocol ButtonSound { } 

到目前爲止,我只設法建立一個沒有任何約束UIButton擴展(這是簡化版本):

// Only when the button conforms to protocol CustomLayer 
extension UIButton { 
    override public class func layerClass() -> AnyClass { return CAShapeLayer.self } 
} 

// Only when the button conforms to protocol ButtonSound 
extension UIButton { 
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     super.touchesBegan(touches, withEvent: event) 

     AudioServicesPlaySystemSound(1104) 
    } 
} 

我已閱讀的文章我可以爲協議本身做一個擴展,使用where子句的類UIButton

extension CustomLayer where Self: UIButton { } 

但後來我不能覆蓋任何方法UIButton本身。

像子類作品,但某些按鈕其他建議不能具有相同的功能:

class A: CustomLayer { } // Can't have ButtonSound, single subclass works 
class B: ButtonSound { } // Can't have CustomLayer, single subclass works 

class C: CustomLayer, ButtonSound { } // Error: multiple inheritance from classes 
+0

不能約束添加一個擴展,因爲它會導致多重繼承的潛力 – Paulw11

+0

你不能只將協議一致性添加到「按鈕」,你可以將它添加到某個「UIButton」子類。所以只需要對這些子類進行擴展。 –

+0

@ Paulw11:我害怕這一點,我注意到在某些情況下創建這個問題時,我有多重繼承。我會留下一些問題,也許可能會出現一些其他建議。感謝你的回答。 –

回答

0
import Foundation 

protocol BackButtonDelegate { 

    func BackButtonAction(sender:UIButton) 
} 

class NavigationBack: UIButton 
{ 
    var delegate : BackButtonDelegate! 

    override func drawRect(rect: CGRect) { 
     self.frame = CGRectMake(0, 0, 60, 60) 
     self.setTitle("Back", forState: .Normal) 
     self.titleLabel?.font = UIFont(name: "Helvetica",size: 12) 
     self.setImage(UIImage(named: "back-arrow"), forState: .Normal) 

     self.addTarget(self, action: #selector(NavigationBack.click(_:)), forControlEvents: UIControlEvents.TouchUpInside) 

    } 
    func click(sender:UIButton) 
    { 
     if delegate != nil 
     { 
      delegate!.BackButtonAction(sender) 
     } 
    } 

}