Swift: Passing a parameter to selector

余生长醉 提交于 2019-12-18 11:57:35

问题


Using Swift 3, Xcode 8.2.1

Method:

func moveToNextTextField(tag: Int) {
   print(tag)
}

The lines below compile fine, but tag has an uninitialized value:

let selector = #selector(moveToNextTextField)
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: selector, userInfo: nil, repeats: false)

However, I need to pass a parameter. Below fails to compile:

let selector = #selector(moveToNextTextField(tag: 2))

Swift Compile Error:
Argument of #selector does not refer to an @objc method, property, or initializer.

How can I pass an argument to a selector?


回答1:


#selector describes method signature only. In your case the correct way to initialize the selector is

let selector = #selector(moveToNextTextField(tag:))

Timer has the common target-action mechanism. Target is usually self and action is a method that takes one parameter sender: Timer. You should save additional data to userInfo dictionary, and extract it from sender parameter in the method:

func moveToNextTextField(sender: Timer) {
   print(sender.userInfo?["tag"])
}
...
let selector = #selector(moveToNextTextField(sender:))
Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: selector, userInfo: ["tag": 2], repeats: false)



回答2:


You cannot pass a custom parameter through a Timer action.

Either

#selector(moveToNextTextField)
...
func moveToNextTextField()

or

#selector(moveToNextTextField(_:))
...
func moveToNextTextField(_ timer : Timer)

is supported, nothing else.

To pass custom parameters use the userInfo dictionary.



来源:https://stackoverflow.com/questions/41987324/swift-passing-a-parameter-to-selector

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