UITableview: How to Disable Selection for Some Rows but Not Others
You just have to put this code into cellForRowAtIndexPath
To disable the cell's selection property: (while tapping the cell)
cell.selectionStyle = UITableViewCellSelectionStyleNone;
To enable being able to select (tap) the cell: (tapping the cell)
// Default style
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
// Gray style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
Note that a cell with selectionStyle = UITableViewCellSelectionStyleNone;
will still cause the UI to call didSelectRowAtIndexPath
when touched by the user. To avoid this, do as suggested below and set.
cell.userInteractionEnabled = NO;
instead. Also note you may want to set cell.textLabel.enabled = NO;
to gray out the item.
If you want to make a row (or subset of rows) non-selectable, implement the UITableViewDelegate
method -tableView:willSelectRowAtIndexPath:
(also mentioned by TechZen). If the indexPath
should be not be selectable, return nil
, otherwise return the indexPath
. To get the default selection behavior, you just return the indexPath
passed to your delegate
method, but you can also alter the row selection by returning a different indexPath
.
example:
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// rows in section 0 should not be selectable
if ( indexPath.section == 0 ) return nil;
// first 3 rows in any section should not be selectable
if ( indexPath.row <= 2 ) return nil;
// By default, allow row to be selected
return indexPath;
}