Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Tag from Tap Gesture Recognizer

I've got an array of UIImageViews and have programmatically assigned tap gesture recognizers to them.

    myImages.forEach{ UIImageView in
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(gesture:)))
        tap.numberOfTapsRequired = 1
        tap.delegate = self
        view.addGestureRecognizer(tap)
        }

What's the best way to assign a sender to each (or determine which image was tapped another way)? I've unsuccessfully tried

var tag = sender.view!.tag

Thanks!

like image 481
moosgrn Avatar asked Dec 14 '22 12:12

moosgrn


1 Answers

in here you need to follow two steps,

step 1

assign the tags for imageview before append to your myImages array.

step 2

get the tag from imageview array and assign to your each gesture

myImages.forEach{  
    let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        tap.numberOfTapsRequired = 1
        tap.view?.tag =  $0.tag
        $0.isUserInteractionEnabled = true
        $0.addGestureRecognizer(tap)
    }

and handle the func like

  @objc func handleTap(_ sender: UITapGestureRecognizer) {
     guard let getTag = sender.view?.tag else { return }
    print("getTag == \(getTag)")
}
like image 72
Anbu.Karthik Avatar answered Jan 16 '23 01:01

Anbu.Karthik