Swift - 协议作为按钮动作的目标类型 [英] Swift - protocol as type as target of button action
问题描述
我正在尝试创建 - HeaderView,它是 UIView 的子类,它包含一个关闭按钮和一个标题标签.
I am trying to create - HeaderView which is subclass of UIView, it contains a close button and a title label.
class HeaderView: UIView {
private var titleLabel: UILabel!
private var closeButton: UIButton!
}
我不想将 self 添加为 closeButton 操作的目标,而是想将 myViewController 设置为其目标,而且我希望 HeaderView 类可重用.
I don't want to add self as target of closeButton action but want to set myViewController as its target, moreover I want HeaderView class to be reusable.
所以我声明了一个协议:
So I declared a protocol:
protocol CloseViewProtocol {
func closeViewAction(sender: UIButton!)
}
并声明一个这样的变量:
And declared a variable like this:
class HeaderView: UIView {
private var titleLabel: UILabel!
private var closeButton: UIButton!
var closeButtonTarget: CloseViewProtocol?
}
强制(在编译时)closeButtonTarget 实现 closeViewAction: 方法.
to enforce (at compile time) that closeButtonTarget implements closeViewAction: method.
现在我不能这样做:
closeButton.addTarget(closeButtonTarget, action: "closeViewAction:", forControlEvents: .TouchUpInside)
做哪个编译器抱怨 -
doing which compiler complains -
Cannot convert value of type 'CloseViewProtocol?' to expected argument type 'AnyObject?'
要解决这个问题,我可以这样做:
To resolve this I can do this:
let buttonTarget = closeButtonTarget as! UIViewController
closeButton.addTarget(buttonTarget, action: "closeViewAction:", forControlEvents: .TouchUpInside)
有没有更好的方法来实现预期的行为?
Is there any better way to achieve expected behavior?
推荐答案
我喜欢 Andrius 方法,但要回答这个问题,您必须将 class
关键字添加到协议的继承列表中:>
I like Andrius approach, but to answer the question, you have to add the class
keyword to your protocol’s inheritance list:
protocol CloseViewProtocol: class {
func closeViewAction(sender: UIButton!)
}
这篇关于Swift - 协议作为按钮动作的目标类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!