Swift: Passing a parameter to selector

后端 未结 2 1802
别那么骄傲
别那么骄傲 2020-12-29 13:46

Using Swift 3, Xcode 8.2.1

Method:

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

The lines below compile fine, but tag

相关标签:
2条回答
  • 2020-12-29 14:37

    #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)
    
    0 讨论(0)
  • 2020-12-29 14:39

    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.

    0 讨论(0)
提交回复
热议问题