Search code examples
swiftuitableviewtagsuitapgesturerecognizer

Explaination to tag issue in UITapGestureRecognizer


This is not a massive issue with me, I am just struggling to understand what is happening. Other rather how to make it work the way I want it to work.

Consider the following code of any standard UITableViewController:

var tapGestureRecognizer = UITapGestureRecognizer()

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    guard let customCell = tableView.dequeueReusableCell(withIdentifier: customCellID) as? CustomTableViewCell else { return UITableViewCell() }
    
    if indexPath.row == 0 {

        print("Inside cellForRowAt: \(indexPath.row)")

        customCell.backgroundColor = .red
        
        tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tagIndexPathRowMethod))
        tapGestureRecognizer.cancelsTouchesInView = false
        tapGestureRecognizer.view?.tag = indexPath.row
        
        customCell.isUserInteractionEnabled = true
        customCell.addGestureRecognizer(tapGestureRecognizer)
        
        return customCell
        
    } else {

        print("Inside cellForRowAt: \(indexPath.row)")

        customCell.backgroundColor = .blue
        
        tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tagIndexPathRowMethod))
        tapGestureRecognizer.cancelsTouchesInView = false
        tapGestureRecognizer.view?.tag = indexPath.row
        
        customCell.isUserInteractionEnabled = true
        customCell.addGestureRecognizer(tapGestureRecognizer)
        
        return customCell
    }
}

@objc private func tagIndexPathRowMethod(sender: UITapGestureRecognizer) {
    print("Cell number tag: \(String(describing: sender.view?.tag))")
}

I've already tried splitting the properties, methods and cells into separate codes such as

var firstTapGestureRecognizer = UITapGestureRecognizer()
var secondTapGestureRecognizer = UITapGestureRecognizer()

etc, but the tag still prints only a 0 from both cells.

Could someone explain to me how to make the print statement in tagIndexPathRowMethod returns 0 as tag no matter if I tap in cell 0 or cell 1, but the print statements inside cellForRowAt prints the correct indexPath.row integers, 0 and 1? I know I could use didSelectRowAt, but I've just become stubborn I guess.

(I'm well aware of all times I'm breaking with the DRY principle, but it just serves as a pedagogical example.)


Solution

    • Updated answer

    This happening because the you setting tag before adding gestures to the cell. In this case, tapGestureRecognizer.view is null at that time. Just do one thing set tag after adding gestures to the cell.

       customCell.addGestureRecognizer(tapGestureRecognizer)
       
       tapGestureRecognizer.view?.tag = indexPath.row