Karl Kivi
Karl Kivi

Reputation: 145

How to cancel table cell selection

All my table cells are selection is allowed, but is it possible to cancel table cell action touch before (this function) tableView(tableVIew: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) gets informed that cell's been selected?

Upvotes: 0

Views: 1699

Answers (3)

Christian
Christian

Reputation: 367

If you want to cancel the selection, you can implement func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? to react to the selection event.

The following code will cancel the selection for the first row of a section:

func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
    if (indexPath.row == 0) {
        return nil
    }
    return indexPath
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("SELECTED!!!")
}

You may also have a look at func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool and implement this method, if you want to avoid the highlighting of the cell.

Upvotes: 4

Viru1987
Viru1987

Reputation: 13

No, You can't stop the delegate to be called
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

You can use following delegate to disable the selection

  • (void)selectRowAtIndexPath:(nullable NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition;

  • (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;

  • (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

OR you can place validation to control the behaviour
if( indexPath.section == 0 ) return nil;

Upvotes: 0

sschale
sschale

Reputation: 5188

There is the method -(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath which can prevent highlighting the cell, but you can't prevent the selection if you have the cell enabled.

You can either

  1. Dynamically set cells to be enabled or not during your app's execution.
  2. Prevent highlighting of the cell you don't want to select by returning false in shouldHighlightRowAtIndexPath, and then immediately in didSelectRowAtIndexPath break before any execution happens.

Upvotes: 1

Related Questions