Syed Tariq
Syed Tariq

Reputation: 2918

How can I detect which custom button was tapped in a bank of custom buttons in ios

I have a bank of 6 custom buttons which I implemented using images with user interaction enabled. I also added a tag to each switch. I attached a tap gesture recognizer to each button. I used a techniques described in detect view was tapped When I press any of the buttons I always get the last button that the gesture was attached to. Here is the code. Help would be appreciated.

import UIKit
class HomeViewController: UIViewController {
@IBOutlet var buttonImages: [UIImageView]!

var selectedOption = 0

@IBAction func tapped(sender: UITapGestureRecognizer) {
    let buttonImage = sender.view!
    println("Tag: \(buttonImage.tag) image: \(buttonImage)")
    selectedOption = (sender.view?.tag)!
    println("tapped: \(selectedOption)")
}
override func viewDidLoad() {
    super.viewDidLoad()


    let tapGestureRecognizer = UITapGestureRecognizer(target: self,
        action: "tapped:")
    tapGestureRecognizer.numberOfTouchesRequired = 1
    tapGestureRecognizer.numberOfTapsRequired = 1
    let x = UIImage(named:"TV normal.png") // replace with array

    var tag = 0
    for buttonImage in buttonImages {
        buttonImage.addGestureRecognizer(tapGestureRecognizer)
        buttonImage.image = x
        buttonImage.tag = tag
        tag++
    }
    // check
    for buttonImage in buttonImages {
        println("Tag: \(buttonImage.tag) image: \(buttonImage)")
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

Upvotes: 0

Views: 210

Answers (1)

tbaranes
tbaranes

Reputation: 3590

Your issue is due to the fact you are attaching the same UITapGestureRecognizer for each UIImage, but a gesture can be attached to only one UIView at the same time, that's why you always getting back the last one.

In your case, you just need to create a new UITapGestureRecognizer for each UIImage you are creating with the same target / action. This way, your method tapped will work.

Upvotes: 1

Related Questions