我试图创建一个协议,这样我就可以让我的一些按钮符合这个协议,并在调用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()
}
}
这样做有效,但这意味着我每次使用协议touchesBegan
时都必须手动覆盖AddSound
。
是否有可能在touchesBegan
的扩展名中覆盖AddSound
甚至是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()
}
}
答案 0 :(得分:0)
protocol AddSound: class {
func addSound()
}
extension UIButton: AddSound {
func addSound() { print("play some sound") }
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
addSound()
print("touchesBegan")
}
}
class ViewController: UIViewController {
var button = UIButton(frame: CGRect(x: 40, y: 40, width: 80, height: 40))
override func viewDidLoad() {
super.viewDidLoad()
button.setTitle("Button", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
view.addSubview(button)
}
}
protocol AddSound: class {
func addSound()
}
class MyButton: UIButton, AddSound {
func addSound() { print("play some sound") }
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
addSound()
print("touchesBegan")
}
}
....
var button = MyButton(frame: CGRect(x: 40, y: 40, width: 80, height: 40))
....
点击按钮,您将看到: