我想知道我们能否在 swift 中实现强类型选择器?例如,如果我稍后在我的 View Controller 中有一个名为 buttonTapped(sender: AnyObject)
的方法,当我们将该方法作为目标添加到某个按钮时,我们可以说
button.addTarget(self, selector:ViewController.buttonTapped(self), forControlEvents: .TouchUpInside)
最佳答案
过时了。参见 Claus Jørgensen's answer适用于 Swift 2.2+
Swift 中没有“选择器”的概念。理想情况下,应将闭包用于此目的。
你真正想要的是这样的
button.addAction(forControlEvents: .TouchUpInside) {
// watch out for retain cycle, use weak or unowned accordingly
ViewController.buttonTapped(self)
}
你可以用这段代码得到它(未经测试,但它应该给你一个起点)
public class ClosureWrapper : NSObject
{
let _callback : Void -> Void
init(callback : Void -> Void) {
_callback = callback
}
public func invoke()
{
_callback()
}
}
var AssociatedObjectHandle: UInt8 = 0
extension UIControl
{
public func addAction(forControlEvents events: UIControlEvents, withCallback callback: Void -> Void)
{
let wrapper = ClosureWrapper(callback)
addTarget(wrapper, action:"invoke", forControlEvents: events)
// as @newacct said in comment, we need to retain wrapper object
// this only support 1 target, you can use array to support multiple target objects
objc_setAssociatedObject(self, &AssociatedObjectHandle, wrapper, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
希望在未来的SDK版本中,Apple会添加类似的方法采用闭包代替选择器,这样我们就不需要自己实现了。
关于ios - swift 中的强类型选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26449053/