2016-04-23 38 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) 
     } 
    } 

}