CoderChick
CoderChick

Reputation: 232

Swift recognize tableView cell tap area

How can I detect a particular area tapped of a tableView cell porgrmatically?

For example, if the user taps the left half of the tableView Cell, didSelectRowAt is called and recognizes the left half of the cell.

Pseudo:

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

    print("Entire cell tapped")

    if(left side of cell pressed){
      //cell.width /2
      print("left side half of cell pressed")
   }
}

Upvotes: 0

Views: 930

Answers (1)

Visal Rajapakse
Visal Rajapakse

Reputation: 2042

According to this thread, adding a Gesture recognizer can conflict with the TableView interactions.

Hence, To achieve what you require, you will have to add a gesture recognizer to the contentView of the UITableViewCell and get the tapped location of the gesture. For this,

  1. First, Define the UITapGestureRecognizer and the action within the UITableViewCell class. Refer the following code
    lazy var tap = UITapGestureRecognizer(target: self, action: #selector(didTapScreen))
.
.
.
    // Gesture action
    @objc func didTapScreen(touch: UITapGestureRecognizer) {
        let xLoc = touch.location(in: self.contentView).x // Getting the location of tap
        if xLoc > contentView.bounds.width/2 {
            // RIGHT
        } else {
            // LEFT
        }
    }
  1. Add the following to the init() method of the custom cell as follows
    override init(frame: CGRect) {
        super.init(frame: frame)
        tap.numberOfTapsRequired = 1
        contentView.addGestureRecognizer(tap)
        // Other setups
    }

I tried the code in a UICollectionViewCell and got the following output

enter image description here

Upvotes: 1

Related Questions