简体   繁体   中英

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!

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)")
}

You can use the block provided by UITapGestureRecognizer init to access your images in place.

myImages.forEach { image in
let tap = UITapGestureRecognizer(block: {[weak self] _ in
       //Do your stuff here
       //print("Image Tapped:", image.debugDescription)
}, delegate: self)
tap.numberOfTapsRequired = 1
image.addGestureRecognizer(tap)
}

If you want to set UITapGestureRecognizer in UICollectionView or UITableView cell then below solution is useful for us.

Step 1 Assign the UITapGestureRecognizer to particuller textview or other view in UICollectionView or UITableView cell.

cell.textView?.delegate = self
cell.textView?.isEditable = false
cell.textView?.isSelectable = true
let tap = UITapGestureRecognizer(target: self, action:#selector(self.onclickLink(_:)))
cell.textView?.tag = indexPath.row
tap.numberOfTapsRequired = 1
cell.textView?.addGestureRecognizer(tap)

Step 2 Get the tag from UITextView or other View in onclick action.

    @IBAction func onclickLink(_ sender: UITapGestureRecognizer) {
        print("indexPathRow == \(sender.view?.tag ?? 0)")            
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM