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


当前回答

场景- 1

如果你不想在表视图中选择某些特定的单元格,你可以在cellForRow函数中为这些单元格设置选择样式。

objective - c

cell.selectionStyle = UITableViewCellSelectionStyleNone;

斯威夫特4.2

cell.selectionStyle = .none

场景- 2

禁用整个表视图的选择:

objective - c

self.tableView.allowsSelection = false;

斯威夫特4.2

self.tableView.allowsSelection = false

其他回答

我们可以编写这样的代码

 cell.selectionStyle = UITableViewCellSelectionStyleNone;

但当我们有自定义单元格xib时,在该行上面给出警告

自定义单元格xib

我们需要从界面构建器中设置选择样式为None

在UITableViewDelegate协议中,你可以使用willSelectRowAtIndexPath方法 如果你不希望行被选中,返回nil。

同样的,你可以使用willDeselectRowAtIndexPath方法并返回nil,如果你不想让行取消选择。

快速解决方案,自定义单元:

import Foundation

class CustomTableViewCell: UITableViewCell
{
  required init(coder aDecoder: NSCoder)
  {
    fatalError("init(coder:) has not been implemented")
  }

  override init(style: UITableViewCellStyle, reuseIdentifier: String?)
  {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    self.selectionStyle = UITableViewCellSelectionStyle.None
  } 
}

直接禁用突出显示TableViewCell到故事板

编辑:对于更新的Swift,它被更改为:

cell.selectionStyle = .none

更多信息请看这个: https://developer.apple.com/documentation/uikit/uitableviewcell/selectionstyle

如果有人需要斯威夫特的答案:

cell.selectionStyle = .None