具有目标选择器的快速访问控制 [英] Swift access control with target selectors
问题描述
看看这个示例代码:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let letterButton = UIButton.buttonWithType(.Custom) as UIButton
self.view.addSubview(letterButton)
letterButton.addTarget(self, action:Selector("buttonDidTap:"), forControlEvents: .TouchUpInside)
}
func buttonDidTap(button: UIButton!) {
print(button.char)
}
}
只要Selector是 public 或 internal ,UIButton
的目标操作就可以正常工作,但是如果它是 private ,则会崩溃由于无法识别的选择器发送到实例
The target action for the UIButton
works fine as long as Selector is public or internal, but if it's private, it crashes due to unrecognized selector sent to instance
有什么办法可以做到这一点?我不想公开水龙头功能或内部水龙头.
Is there any way I can achieve this ? I don't want to make tap function public or internal.
推荐答案
您需要@objc
才能将私有方法公开给objc运行时
you need @objc
to expose a private method to objc runtime
@objc private func buttonDidTap(button:UIButton!) {
println(button.char)
}
标记为私有的声明不会在Objective-C运行时公开 如果没有其他注释. IB出口,IB行动和核心数据 托管属性无论其访问权限如何,始终向Objective-C公开 等级.如果您需要可从中调用的私有方法或属性 Objective-C(例如使用基于选择器的较旧API的 回调),将@objc属性显式添加到声明中. !
Declarations marked private are not exposed to the Objective-C runtime if not otherwise annotated. IB outlets, IB actions, and Core Data managed properties remain exposed to Objective-C whatever their access level. If you need a private method or property to be callable from Objective-C (such as for an older API that uses a selector-based callback), add the @objc attribute to the declaration explicitly.! !
这篇关于具有目标选择器的快速访问控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!