Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

ios - Swift access control with target selectors

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...