Disable selection of a single UITableViewCell

前端 未结 9 2181
迷失自我
迷失自我 2021-01-31 08:32

How do you disable selecting only a single cell in a UITableView? I have several, and I only want the last to be disabled.

9条回答
  •  Happy的楠姐
    2021-01-31 09:11

    Throw this in your custom Table VC:

    // cells lacking UITableViewCellAccessoryDisclosureIndicator will not be selectable
    - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        if (cell.accessoryType != UITableViewCellAccessoryDisclosureIndicator) {
            return nil;
        }
        return indexPath;
    }
    
    // disabled cells will still have userinteraction enabled for their subviews
    - (void)setEnabled:(BOOL)enabled forTableViewCell:(UITableViewCell *)tableViewCell
    {
        tableViewCell.accessoryType = (enabled) ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
        // if you dont want the blue selection on tap, comment out the following line
        tableViewCell.selectionStyle = (enabled) ? UITableViewCellSelectionStyleBlue : UITableViewCellSelectionStyleNone;
    }
    

    Then to enable/disable selection for someTableViewCell, do this:

    [self setEnabled:state forTableViewCell:someTableViewCell];
    

    You're done and can ship.

提交回复
热议问题