Passing arguments to selector in Swift

后端 未结 6 707
闹比i
闹比i 2020-11-27 03:14

I\'m programmatically adding a UITapGestureRecognizer to one of my views:

let gesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap         


        
6条回答
  •  半阙折子戏
    2020-11-27 03:36

    It looks like you're misunderstanding a couple of things.

    When using target/action, the function signature has to have a certain form…

    func doSomething(sender: Any)
    

    or

    func doSomething(sender: Any, forEvent event: UIEvent)
    

    where…

    The sender parameter is the control object sending the action message.

    In your case, the sender is the UITapGestureRecognizer

    Also, #selector() should contain the func signature, and does NOT include passed parameters. So for…

    func handleTap(sender: UIGestureRecognizer) {
    
    }
    

    you should have…

    let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
    

    Assuming the func and the gesture are within a view controller, of which modelObj is a property / ivar, there's no need to pass it with the gesture recogniser, you can just refer to it in handleTap

提交回复
热议问题