如何使UITableView中的单元格无法被选中?

78

我有一个单元格,我要将其插入到UITableView的顶部。如何确保当用户点击该单元格时,它不会显示蓝色的选中指示器?

我应该在单元格上设置selectedBackgroundView属性并将其设置为透明颜色。这样,当用户点击单元格时,它仍然会被选择,但是不会显示任何选中指示器。

<code>cell.selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero]; 
cell.selectedBackgroundView.backgroundColor = [UIColor clearColor]; </code>
15个回答

87

要禁止选择表格中的任何单元格,或基于行索引选择特定的表格单元格,请使用willSelectRowAt

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


        return nil
    }

如果只是想移除元素选中时的UI效果,可以将UITableViewCell的选择样式设置为UITableViewCellSelectionStyleNone

Swift 5:

selectionStyle = .none

85
这并不意味着该单元格变得不可选择,只是在选中时,其视觉外观不会改变。当单元格被点击时,tableView:didSelectRowAtIndexPath: 仍会被调用。如果要实际防止选择,您需要在 UITableViewDelegate 上实现 tableView:willSelectRowAtIndexPath: 并对不可选择的行返回 nil。 - j b
1
Swift 3 - cell.selectionStyle = UITableViewCellSelectionStyle.noneSwift 3 - cell.selectionStyle = UITableViewCellSelectionStyle.none - Johannes Knust
4
简单来说:cell.selectionStyle = .none意思是取消单元格的选中样式。 - spencer.sm

65

要使单元格在每个单元格的基础上完全不能被选择,需要两个步骤:

1- 如其他人所说:

cell.selectionStyle = UITableViewCellSelectionStyleNone;

2- 按照以下方式实现此代理方法:

// Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    if(cell.selectionStyle == UITableViewCellSelectionStyleNone){
        return nil;
    }
    return indexPath;
}

16
从Storyboard为TableView设置如下内容:

选择:无选择

触摸时显示选定项:假

在此输入图片描述


13

你可以做

cell.selectionStyle = UITableViewCellSelectionStyleNone;

1
一个点符号遗漏了。这是修正后的版本: cell.selectionStyle = UITableViewCellSelectionStyle.None。 - Oleg Popov

6

对于Swift 3,您可以使用以下内容:

 cell.isUserInteractionEnabled = false

只需将该代码粘贴到表视图的cellForRowAt indexPath方法中即可,非常简单。 - user8043247
当您想要在表视图上禁用用户交互时,此方法非常有用,否则您可以使用Ben先生分享的方法。 - user8043247
也适用于Swift 4。 - leanne
对我来说它运行良好。应该是正确的答案。另一种方法是在tableView:didSelectRowAtIndexPath委托方法中检测单元格索引,然后什么也不做并返回。 - Yongxiang Ruan
我最喜欢这个答案的部分是你可以在单元格内部声明它。如果您有一个单元格(例如空状态单元格),您永远不希望响应轻拍,那么这是一个很好的方法。 - Maxwell

5

Swift 语法:

cell.selectionStyle = UITableViewCellSelectionStyle.None

5
我将从禁用TableViewCell的角度回答。您可以使用故事板。
XCode版本8.2.1(8C1002)
在故事板上选择TableViewCell,右侧面板-实用程序将显示以下内容。

Utilities Sidebar

进行选择:无

就这些!


5

问题是如何使某些单元格可以选择,而其他单元格则不能。在尝试了许多其他建议之后,我找到了解决方案:

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    if (indexPath.row == 1 || indexPath.row == 2) {
        return indexPath
    }
    return nil        
}

3
myTable.allowsSelection = false

2

Swift 3更新:

cell.selectionStyle = UITableViewCellSelectionStyle.none

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接