Swift - 作为按钮操作目标类型的协议

Swift - protocol as type as target of button action

我正在尝试创建 - HeaderView,它是 UIView 的子class,它包含一个关闭按钮和一个标题标签。

class HeaderView: UIView {
    private var titleLabel: UILabel!
    private var closeButton: UIButton!
}

我不想将 self 添加为 closeButton 操作的目标,而是想将 myViewController 设置为其目标,而且我希望 HeaderView class 可重用。

所以我声明了一个协议:

protocol CloseViewProtocol {
    func closeViewAction(sender: UIButton!)
}

并像这样声明一个变量:

class HeaderView: UIView {
    private var titleLabel: UILabel!
    private var closeButton: UIButton!

    var closeButtonTarget: CloseViewProtocol?
}

强制(在编译时)closeButtonTarget 实现 closeViewAction: 方法。

现在我不能这样做了:

closeButton.addTarget(closeButtonTarget, action: "closeViewAction:", forControlEvents: .TouchUpInside)

做哪个编译器抱怨 -

Cannot convert value of type 'CloseViewProtocol?' to expected argument type 'AnyObject?'

要解决这个问题,我可以这样做:

let buttonTarget = closeButtonTarget as! UIViewController
closeButton.addTarget(buttonTarget, action: "closeViewAction:", forControlEvents: .TouchUpInside)

有没有更好的方法来实现预期的行为?

这有点老派 - 协议委托,新模式是更多的函数式编程 我建议使用闭包

var closeHanlder:()->Void?

然后将按钮作为私有变量放入其中,并在视图控制器中执行

headerViewInstance.closeHandler = self.handleCloseFunction

我应该补充一点,按钮操作在 headerView 中处理,其操作执行所需的操作并调用 closeHandler?()

我喜欢 Andrius 的方法,但要回答这个问题,您必须将 class 关键字添加到协议的继承列表中:

protocol CloseViewProtocol: class {
    func closeViewAction(sender: UIButton!)
}