swiftuitapgesturerecognizeruilongpressgesturerecogni

Swift - How to get the sender tag for an array of buttons using UILongPressGestureRecognizer?


I have buttons in the storyboard that I put into a Referencing Outlet Collection. I'm using UITapGestureRecognizer and UILongPressGestureRecognizer for all of these buttons, but how can I print exactly which button gets tapped? Bellow is what I tried but doesn't work. I get an error that says "Value of type 'UILongPressGestureRecognizer' has no member 'tag'." I'm trying to build the button grid for the Minesweeper game. Thank you for your help.

class ViewController: UIViewController { @IBOutlet var testButtons: [UIButton]! // There are 100 buttons in this array

override func viewDidLoad() {
    super.viewDidLoad()

    let testButtonPressed = UILongPressGestureRecognizer(target: self, action: #selector(testPressed))
    testButtonPressed.minimumPressDuration = 0.5
    // These indexes are just to test how to recognize which button gets pressed
    testButtons[0].addGestureRecognizer(testButtonPressed)
    testButtons[1].addGestureRecognizer(testButtonPressed)

}

@objc func testPressed(_ sender: UILongPressGestureRecognizer) {
    print("Test button was pressed")

    print(sender.tag) // THIS DOESN'T WORK, BUT CONCEPTUALLY THIS IS WHAT I WANT TO DO
}

Solution

  • This error occurs because UILongPressGestureRecognizer object has no tag property

    You can access sender's button in a way like that:

    @objc func testPressed(_ sender: UILongPressGestureRecognizer) {
        guard let button = sender.view as? UIButton else { return }
        print(button.tag)
    }
    

    I think that the best solution to handle button's actions is to add @IBAction (you can add it like @IBOutlet with a minor change - set Action connection type)

    And then in @IBAction block you cann access all button properties (like tag and others)

    enter image description here