当你点击UITableView中的一行时,该行会高亮显示并被选中。是否有可能禁用这个,所以点击一行什么都不做?


当前回答

你可以用这个

cell.selectionStyle = UITableViewCellSelectionStyleNone;

其他回答

对我来说,以下方法效果不错:

tableView.allowsSelection = false

这意味着didselectrow#将无法工作。也就是说,触摸表中的一行,本身不会有任何作用。(因此,很明显,永远不会有选中动画。)

(请注意,如果在单元格上有UIButton或任何其他控件,当然这些控件仍然可以工作。你碰巧在表格单元格上的任何控件,都与UITableView允许你使用didSelectRowAt#“选择一行”的能力完全无关。)

另一点需要注意的是:当UITableView处于编辑模式时,这是无效的。要在编辑模式下限制单元格选择,请使用如下代码:

tableView.allowsSelectionDuringEditing = false 

试着输入:

cell.selected = NO;

它将在需要时取消选择您的行。

在Swift3中…

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let r = indexPath.row
    print("clicked .. \(r)")
    tableView.cellForRow(at: indexPath)?.setSelected(false, animated: true)
}

你可以在(iOS) Xcode 9, Swift 4.0中使用以下代码禁用表格单元格高亮显示

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "OpenTbCell") as! OpenTbCell
        cell.selectionStyle = .none
        return cell


}

在属性检查器中的UITableViewCell的XIB中,将Selection的值设置为None。

根据我自己的实践经验,总结一下我认为的正确答案:

如果你想禁用部分单元格的选择,请使用:

cell.userInteractionEnabled = NO;

除了阻止选择,这也会阻止设置了tableView:didSelectRowAtIndexPath的单元格被调用。(感谢Tony Million的回答,谢谢!)

如果你的单元格中有需要点击的按钮,你需要改为:

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

并且你还需要忽略单元格中的任何点击- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath。

如果你想禁用整个表的选择,使用:

tableView.allowsSelection = NO;

(感谢保罗·德·巴罗斯!)