Swift - 调用自定义委托方法

Swift - Invoke Custom Delegate Method

我正在使用 BMPlayer 库并希望实现自定义控件,对此我有以下 class 确认遵循协议

@objc public protocol BMPlayerControlViewDelegate: class {
    func controlView(controlView: BMPlayerControlView, didChooseDefition index: Int)
    func controlView(controlView: BMPlayerControlView, didPressButton button: UIButton)
    func controlView(controlView: BMPlayerControlView, slider: UISlider, onSliderEvent event: UIControlEvents)
    @objc optional func controlView(controlView: BMPlayerControlView, didChangeVideoPlaybackRate rate: Float)
}

open class BMPlayerControlView: UIView {
    open weak var delegate: BMPlayerControlViewDelegate?
    open weak var player: BMPlayer?

    // Removed rest of the code for clarity

    open func onButtonPressed(_ button: UIButton) {
        autoFadeOutControlViewWithAnimation()
        if let type = ButtonType(rawValue: button.tag) {
            switch type {
            case .play, .replay:
                if playerLastState == .playedToTheEnd {
                    hidePlayToTheEndView()
                }
            default:
                break
            }
        }
        delegate?.controlView(controlView: self, didPressButton: button)
    }
}

我正在扩展 BMPlayerControlView class 以使用以下代码扩展控件视图。

class BMPlayerCustomControlStyle3: BMPlayerControlView {

}

class BMPlayerStyle3: BMPlayer {

    class override func storyBoardCustomControl() -> BMPlayerControlView? {
        return BMPlayerCustomControlStyle3()
    }
}

我的问题是,如何调用 didPressButton 委托方法?我不想覆盖 onButtonPressed,我尝试了以下

extension BMPlayerCustomControlStyle3:BMPlayerControlViewDelegate {

    func controlView(controlView: BMPlayerControlView, didChooseDefition index: Int) {
        
    }

    func controlView(controlView: BMPlayerControlView, didPressButton button: UIButton) {
        print("Did Press Button Invoked")
    }

    func controlView(controlView: BMPlayerControlView, slider: UISlider, onSliderEvent event: UIControlEvents) {
        
    }
}

这似乎不起作用,我在这里缺少什么?

谢谢。

如果你想让你的BMPlayerControlView子类充当委托对象,你还需要设置delegate属性 (并像您已经在做的那样遵守 BMPlayerControlViewDelegate 协议)。

一种方法是 覆盖 子类中的 delegate 超类 属性:

class BMPlayerCustomControlStyle3: BMPlayerControlView {

    override open weak var delegate: BMPlayerControlViewDelegate? {
        get { return self }
        set { /* fatalError("Delegate for internal use only!") */ }
    }
}

当然,当像这样在内部使用委托时,您 根本不会 允许 BMPlayerControlView 客户端使用它。上面被覆盖的 set 确保你在尝试这样做时得到一个错误。