【发布时间】:2016-11-17 23:18:37
【问题描述】:
我正在尝试创建一个协议,以便我可以制作一些按钮以符合此协议并在调用 touchesBegan 时播放声音。
协议如下所示:
protocol AddSound: class {
func addSound()
}
extension AddSound where Self: UIButton {
func addSound() { print("play some sound") }
}
class CustomButton: UIButton, AddSound {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
addSound()
}
}
这可行,但这意味着我每次使用协议AddSound 时都必须手动覆盖touchesBegan。
是否有可能在AddSound 的扩展中覆盖touchesBegan,甚至是UIButton 本身的扩展,符合AddSound 协议?
这不起作用:
extension AddSound where Self: UIButton {
func addSound() { print("playing some sound") }
// can't override touchesBegan
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.touchesBegan(touches, with: event)
addSound()
}
}
【问题讨论】: