[英]Extension UIButton only when conforming to a protocol
I'm trying to create several extensions for UIButton
so I can add some functionality easily just by adding a protocol to a custom button. 我正在尝试为
UIButton
创建多个扩展,以便仅通过向自定义按钮添加协议即可轻松添加一些功能。 It'd be a lot easier if I didn't have to override some methods in UIButton
so I'm thinking I'll have to make an extension for UIButton
itself. 如果我不必重写
UIButton
某些方法会容易UIButton
所以我认为我必须对UIButton
本身进行扩展。
For example, I have several protocols my custom buttons can conform to: 例如,我有几种协议,我的自定义按钮可以符合:
protocol CustomLayer { }
protocol ButtonSound { }
So far I only managed to create an extension for UIButton
without any constraints (these are simplified versions): 到目前为止,我仅设法为
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)
}
}
I've read posts I can make an extension for the protocol itself with a where clause for the class UIButton
: 我读过一些帖子,可以使用
UIButton
类的where子句对协议本身进行扩展:
extension CustomLayer where Self: UIButton { }
But then I can't override any methods of UIButton
itself. 但是,然后我无法覆盖
UIButton
本身的任何方法。
Other suggestions like subclassing works, but certain buttons can't have the same functionality: 其他建议(例如子类化)也可以,但是某些按钮不能具有相同的功能:
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
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)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.