0

I would like to create a messaging app, and therefore I would like to allow users to select the messages.

The problem is that I can not find a way to make it so that cell gets selected only if tapped inside it on a specific view

My source code:

 override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { let cell = tableView.cellForRow(at: indexPath) as! BubbleCell if (cell.messageBubble.wasClicked){ //? somehow return indexPath } else { return nil } } 

Just like in messenger.

If you click on the blank space then the cell wont be selected, but if on the message bubble (inside the cell there's a view for that) then it gets selected.

2 Answers 2

2

It's easiest to see how to do this if we pretend the message bubble is a button. If it isn't a button, you can give it a tap gesture recognizer and get the same effect.

First, use the delegate method to suppress the normal ability of the user to tap the cell to select it:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return nil } 

Second, we've given the button (or tap gesture recognizer) an action function. When it fires, figure out what cell the button is in and select it in code:

@IBAction func buttonPressed (_ sender:AnyObject) { let cell = (sender as! UIView).superview!.superview! as! UITableViewCell let row = self.tableView.indexPath(for: cell)! self.tableView.selectRow(at: row, animated: true, scrollPosition: .none) } 

In that example, I happen to know that the button is directly inside the cell's content view, so it's two steps up the view hierarchy to reach the cell. You might need to make adjustments, of course.

This screencast shows the result: attempting to click on the cell as a whole does nothing, but clicking on the "Button" area selects the cell.

enter image description here

The reason this approach works is that our willSelectRowAt is not called when we select the row in code — only when the user taps on the cell.

Sign up to request clarification or add additional context in comments.

Comments

1

You can remove willSelectRowAt method and add buttons (or views with UITapGestureRecognizer) in your cells.

1 Comment

Add a button over the view.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.