Swift access control with target selectors

拈花ヽ惹草 提交于 2019-11-27 05:24:21

问题


Have a look at this example code:

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

}

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.


回答1:


you need @objc to expose a private method to objc runtime

@objc private func buttonDidTap(button:UIButton!) {
    println(button.char)
}

From Xcode6 beta4 release notes

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.! !



来源:https://stackoverflow.com/questions/25056278/swift-access-control-with-target-selectors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!