gpt4 book ai didi

swift - 在协议(protocol)扩展中覆盖 touchesBegan

转载 作者:行者123 更新时间:2023-11-28 08:23:38 24 4
gpt4 key购买 nike

我正在尝试创建一个协议(protocol),这样我就可以让我的一些按钮符合这个协议(protocol),并在调用 touchesBegan 时播放声音。

协议(protocol)看起来像这样:

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()
}
}

这可行,但这意味着我每次使用协议(protocol) AddSound 时都必须手动覆盖 touchesBegan

是否有可能在 AddSound 的扩展中覆盖 touchesBegan 或者甚至是 UIButton 本身的扩展,符合协议(protocol) 添加声音?

这行不通:

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()
}
}

最佳答案

方式一

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))
....

结果

点击按钮,你会看到:

enter image description here

关于swift - 在协议(protocol)扩展中覆盖 touchesBegan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40666791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com