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

2024-03-05

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

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

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

所以我声明了一个协议:

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)

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


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

protocol CloseViewProtocol: class {
    func closeViewAction(sender: UIButton!)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift - 协议作为按钮操作的目标类型 的相关文章

随机推荐