0

I have an UITableView that has multiple rows. The user is only allowed to select 1 row. I want to show the grey selection effect only while touching the row, not after the row is selected.

I set the selection effect to Grey in interface builder. This allows me to see the selection effect while touching, but it also shows the grey selection color after I made my selection. To fix this I tried the following code from https://stackoverflow.com/a/10402278/6414904:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath) as! AnswerTableViewCell
    tableView.deselectRow(at: indexPath, animated: true)
}

This works partly. When I select a cell it only shows the Grey selection effect while touching the cell but after selecting a cell the grey selection effect is gone. This is what I want but with this code added it also allows the user to select multiple rows which I do not want. With this approach I also can't use the didDeselectRowAt method for other functionalities.

How do I create a selection effect which only shows during touch/hold but is removed after a selection while only allowing 1 row to be selected at all times?

Community
  • 1
  • 1
Hapeki
  • 2,153
  • 1
  • 20
  • 36
  • `UITableView` has a property `allowsMultipleSelection`, it's probably set to `true` in your case. Set it to `false` in code or set `Selection` to be `Single Selection` for the table in the interface builder. – ovejka Dec 21 '16 at 18:58
  • @ovejka this property is already set to Single Selection in IB. The weird part is that with the above code it does allow multiple selections. Removing the `deselectRow` method brings it back to single selection. – Hapeki Dec 21 '16 at 19:04
  • remove `let cell = self.tableView.cellForRow(at: indexPath) as! AnswerTableViewCell` and see if it makes difference. You don't seem to be using it anyway. – Andrii Chernenko Dec 21 '16 at 19:42
  • this doesn't affect the desired goal @deville – Hapeki Dec 21 '16 at 22:24

2 Answers2

1

For this specially one delegate method is available.

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {


 // do something here
}
Sivajee Battina
  • 4,124
  • 2
  • 22
  • 45
  • This allows me to highlight the selected cell, however if the cell is quickly touched the effect of it being clicked doesn't show. – Hapeki Dec 21 '16 at 19:03
0

Add cell.setHighlighted(false, animated:true) to your didSelectRow call.

If I'm not mistaken, didSelectRow is only called after you release the button.

Jake T.
  • 4,308
  • 2
  • 20
  • 48