【问题标题】:Override touchesBegan in protocol extension在协议扩展中覆盖 touchesBegan
【发布时间】: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()
    }
}

【问题讨论】:

    标签: swift protocols


    【解决方案1】:

    方式 1

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

    方式 2

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

    结果

    点击按钮,你会看到:

    【讨论】:

    • 在您的回答中,所有UIButton 都会受到影响并具有AddSound。我只想要符合AddSound 协议的按钮来发出声音。我读过协议扩展并不意味着覆盖方法,所以我必须找到其他解决方案。
    • 您找到问题的解决方案了吗?
    猜你喜欢
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多