在协议扩展

时间:2016-11-17 23:18:37

标签: swift protocols

我试图创建一个协议,这样我就可以让我的一些按钮符合这个协议,并在调用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()
    }
}

1 个答案:

答案 0 :(得分:0)

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

结果

点击按钮,您将看到:

enter image description here