扩展UIKit委托协议

时间:2018-04-04 14:36:25

标签: swift

我试图在UIPickerViewDelegate协议中添加一个新的可选方法,但是当调用该方法时,它会调用默认方法而不是实现的方法。这样的事情可能吗?

extension UIPickerViewDelegate {

    func doneClicked(_ pickerView: UIPickerView, selectedRow: Int, inComponent component: Int) {/* default */}
}

extension UIPickerView {

    func toolbar() -> UIToolbar? {

        let toolBar = UIToolbar()

        toolBar.barStyle = UIBarStyle.default
        toolBar.isTranslucent = true
        toolBar.tintColor = UIColor.black
        toolBar.sizeToFit()

        let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.doneButtonClicked))
        let spacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)

        toolBar.setItems([spacer, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true

        return toolBar
    }

    @objc func doneButtonClicked() {

        if let delegate = self.delegate {

            delegate.doneClicked(self, selectedRow: self.selectedRow(inComponent: 0), inComponent: 0)
        }
    }
}

问题是当调用doneClicked()时,只会执行扩展中的默认方法。我认为如果协议符合类实现了该函数,那么Swift不会调用默认方法。

1 个答案:

答案 0 :(得分:1)

因为UIPickerView中的委托属于UIPickerViewDelegate类型。 尝试像这样投射:

if let delegate = self.delegate as? MyViewController {
    delegate.foo()
}