在swift中的强类型选择器 [英] Strongly typed selectors in swift
问题描述
buttonTapped(sender:AnyObject)
的方法,当我们将该方法作为目标添加到某个按钮时,我们可以 button.addTarget(self,selector:ViewController.buttonTapped(self),forControlEvents:.TouchUpInside)
Swift 2.2有编译时检查选择器使用 #selector
语法,请参见 https://swift.org/blog/swift- 2-2-new-features / 和使用Swift与Cocoa和Objective-C(Swift 2.2)
,它将是这样写的:
button.addTarget(self,selector:#selector(ViewController.buttonTapped(_ :)),forControlEvents :.TouchUpInside)
I wonder can we implement strongly typed selectors in swift? For example if i have a method named buttonTapped(sender: AnyObject)
in my view controller later when we add that method as target to some button can we just say
button.addTarget(self, selector:ViewController.buttonTapped(self), forControlEvents: .TouchUpInside)
Swift 2.2 have compile time checked selectors using the #selector
syntax, see https://swift.org/blog/swift-2-2-new-features/ and Using Swift with Cocoa and Objective-C (Swift 2.2)
For your example, it would be written this way:
button.addTarget(self, selector: #selector(ViewController.buttonTapped(_:)), forControlEvents: .TouchUpInside)
这篇关于在swift中的强类型选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!