我正在尝试为 UIButton
创建多个扩展,这样我只需向自定义按钮添加协议(protocol)即可轻松添加一些功能。如果我不必重写 UIButton
中的某些方法,那就容易多了,所以我想我必须为 UIButton
本身进行扩展。
例如,我的自定义按钮可以遵循多个协议(protocol):
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 子句为协议(protocol)本身进行扩展:
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
最佳答案
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)
}
}
}
关于ios - 仅当符合协议(protocol)时才扩展 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36817209/