TapRecognizer on UIKit problem with a selector

Hi guys, I hope you're doing well.
Task: I'm trying to make a func that takes actions depending on how many times you tap on a view. The function takes a number of taps as a parameter.
Problem: I counter a compiler-time error, the text is as follows "Argument of '#selector' does not refer to an '@objc' method, property, or initializer"

class ViewController: UIViewController {
    
    var label: UILabel = {
        let labelIn = UILabel(frame: CGRect(x: 0, y: 40 , width: UIScreen.main.bounds.width, height: 40))
        labelIn.backgroundColor = .orange
        labelIn.textColor = .blue
        labelIn.textAlignment = .center
        labelIn.text = "Do some gesture."
        return labelIn
    }()
    override func viewDidLoad() {
        view.addSubview(label)
        view.backgroundColor = .orange
        tapGestureRecognizer(times: 2)
        tapGestureRecognizer(times: 3)
        tapGestureRecognizer(times: 4)
        tapGestureRecognizer(times: 5)
    }
    func tapGestureRecognizer(times: Int){
        let recognizer = UITapGestureRecognizer(target: self,
                                                action: #selector(tabAction(taps: times )))
        recognizer.numberOfTapsRequired = times
        self.view.addGestureRecognizer(recognizer)
    }
    @objc func tabAction(taps: Int){
        switch taps {
        case 1:
            label.text = "One tap"
        case 2:
            label.text = "Double tap"
        case let x where x > 2:
            print("More than two")
        case let x where x > 2:
            label.text = "You tapped \(x) times"
        default:
            print("default switch")
        }
    }
}

Any help is highly appreciated! Have a good one.

If you just want to get rid of the error message write this for the action argument:

#selector(tabAction(taps:))

UITapGestureRecognizer will call function tabAction when it recognizes a gesture. If you write #selector(tabAction(taps: times)) then you call the function tabAction and get a Void which is not a method, property or initializer, hence the error from the compiler.

To have different actions depending on the number of taps you can write a separate function for each possible number of taps that you wish to recognize. Alternatively, you can try to create an object which will accept the number of taps as a parameter to its init and provide an action depending on the parameter.

Note, that with your code, if you tap 5 times, then all of your gesture recognizers will trigger.

You might want to implement a custom gesture recognizer.

1 Like

I highly appreciate your help, that’s exactly what I needed to hear. :slightly_smiling_face:

Спасибо :)