josephine
josephine

Reputation: 77

ONLY double tap on UITableView Swift 3.0

I would like my tableView to only react to double taps and not at all to single taps. I am currently using the following code:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(singleTap))
    tapGesture.numberOfTapsRequired = 1
    view.addGestureRecognizer(tapGesture)

    let doubleTapGesture = UITapGestureRecognizer()
    doubleTapGesture.numberOfTapsRequired = 2
    view.addGestureRecognizer(doubleTapGesture)

    tapGesture.require(toFail: doubleTapGesture)

    // implement what to do

    if userInfo[indexPath.row].identifier == "username" {
        editUsername()
    }
}

func singleTap() {
    // DO NOTHING
}

So basically I have been trying to "redirect" the single tap to a function that does nothing. However, I find that (in the simulator), the tableView sometimes reacts to the single tap, sometimes not. Any help to solve this issue is highly appreciated!

Upvotes: 1

Views: 760

Answers (1)

Stacy Smith
Stacy Smith

Reputation: 540

To achieve your goal:

  1. Add tap gesture recognizer on your table view, do not forget to set numberOfTapsRequired = 2
  2. Do not implement didSelectRowAtIndexPath method
  3. To prevent table view cells from changing their background color after single tap, set in interface builder, Attributes Inspector tab, table view "selection" attribute to "No selection" or table view cell "selection" attribute to "None".

If you want to get indexpath of cell being doubletapped, in your gesture recognizer handler method get tap location in tap.view and use indexPathForRowAtPoint method of tableView:

let tapLocationPoint = tap.location(in: tap.view) 
let tappedCellIndexPath = tableView.indexPathForRow(at: tapLocationPoint)

Upvotes: 1

Related Questions