我正在尝试为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)
}
}
我已阅读帖子我可以通过类UIButton
的where子句为协议本身做一个扩展:
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 :(得分: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)
}
}
}