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
不能約束添加一個擴展,因爲它會導致多重繼承的潛力 – Paulw11
你不能只將協議一致性添加到「按鈕」,你可以將它添加到某個「UIButton」子類。所以只需要對這些子類進行擴展。 –
@ Paulw11:我害怕這一點,我注意到在某些情況下創建這個問題時,我有多重繼承。我會留下一些問題,也許可能會出現一些其他建議。感謝你的回答。 –