具有目标选择器的快速访问控制 [英] Swift access control with target selectors

查看:64
本文介绍了具有目标选择器的快速访问控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这个示例代码:

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)
}

来自 Xcode6 beta4发行说明

标记为私有的声明不会在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆