首页 > 解决方案 > 使用带有多个参数的 @objc 委托方法

问题描述

我希望能够将多个参数传递给一个#selector()方法,而不仅仅是发送者本身。

说,我有一个UITextFieldwhich 有一个UITapGestureRecognizer,我希望其他班级成为 this 的代表UITapGestureRecognizer。我为它编写了一个委托协议,称为SomeDelegateProcotol. 但是,我还想在点击时将 UITextField 的实例传递给委托。我想事情可能看起来像这样:

// The delegate
class Delegate: SomeDelegateProcotol {

    private let textField = TextField()

    func handleTapFromView(_ sender: UITapGestureRecognizer, textField: UITextField) {
        print("Hey! I should handle the tap from the user.")
    }

    init() {
       textField.delegate = self
    }
}
// The protocol
@objc protocol SomeDelegateProtocol {
    @objc func handletapFromView(_ sender: UITapGestureRecognizer, textField: UITextField)
}
class TextField: UITextField {
    weak var delegate: SomeDelegateProtocol?

    override init(frame: CGSize) {
        super.init(frame: frame)
        ...
        let gestureRecognizer = UITapGestureRecognizer(target: delegate!, 
            action: #selector(delegate!.handleTapFromView(_:, textField: 
            self)))
    } 
}

但是,这不是正确的语法,因为handleTapFromView(_:, textField: self)它是无效的。这引发了以下我尚未找到解决方案的问题:

标签: iosswift

解决方案


I would suggest keeping things as simple as this,

protocol SomeDelegateProtocol: class {
    func handletapFromView(_ sender: UITapGestureRecognizer, textField: UITextField)
}

class TextField: UITextField {
    weak var someDelegate: SomeDelegateProtocol?

    override init(frame: CGRect) {
        super.init(frame: frame)

        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tap(_:)))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc private func tap(_ sender: UITapGestureRecognizer) {
        self.someDelegate?.handletapFromView(sender, textField: self)
    }
}

推荐阅读