【问题标题】:IOS/Swift: Make tableview cells not selectable but tableview still scrollable in Swift [duplicate]IOS / Swift:使tableview单元格不可选但tableview在Swift中仍然可以滚动[重复]
【发布时间】:2019-02-20 16:48:08
【问题描述】:

我想让 tableView 的单元格不可选,但仍允许滚动。当我放置

 tableView.isUserInteractionEnabled = false

viewDidLoad 的一些答案中推荐,它可以防止选择但也可以防止滚动。

添加:

 cell.selectionStyle = .none

下面的cellforrowatindexpath 对我没有任何影响。

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

        self.tableView.beginUpdates()
        self.tableView.endUpdates()

        if let cell = tableView.dequeueReusableCell(withIdentifier: "myMessageCell", for: indexPath) as? myMessageCell {
            cell.message = messages[indexPath.row]
            cell.selectionStyle = .none
        }

        return tableView.dequeueReusableCell(withIdentifier: "myMessageCell", for: indexPath)
    }

谁能建议如何在不阻止滚动的情况下阻止选择?

提前感谢您的任何建议。

【问题讨论】:

  • 现在选择单元格时会发生什么?颜色变了?应该解决的是您将selectionStyle 设置为.none
  • “对我没有任何影响”?你期待什么效果?发生了什么?
  • 单元格是否突出显示。将在上面添加更多代码。我期待它不会改变颜色,例如突出显示。
  • 为什么是self.tableView.beginUpdates(), self.tableView.endUpdates()
  • 另外,如果您知道reuseIdentifier "myMessageCell" 将始终返回myMessageCell,那么这是使用as! myMessageCell 的合适位置。您的故事板中可能存在强制展开会发现的问题。

标签: ios swift tableview


【解决方案1】:

希望你正在寻找这个:

tableView.allowsSelection = false

【讨论】:

  • 这完成了工作。谢谢!
  • @user6631314 这将让您禁用选择,但如果您仍然遵循问题中的cellForRowAt 代码,您的单元格数据将会丢失。
【解决方案2】:

问题是您没有返回与您正在出列相同单元格。相反,您将另一个单元格出列并返回它,它没有您设置的任何属性。

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

    if let cell = tableView.dequeueReusableCell(withIdentifier: "myMessageCell", for: indexPath) as? myMessageCell {
        cell.message = messages[indexPath.row]
        cell.selectionStyle = .none
        return cell // Return the cell here instead
    }

    // return tableView.dequeueReusableCell(withIdentifier: "myMessageCell", for: indexPath) // Return another cell which has none of your properties set.
    return UITableViewCell() // return default cell in case your cell is not dequeued
}

【讨论】:

  • 单元格返回正确的值。我认为我不能返回自定义的通用单元格。
  • @user6631314 试试看。它已经在 if let 行中出列。
  • @user6631314 如果具有“myMessageCell”的第一个返回正确出列,则将执行第一个返回,而不会执行第二个出列。第二个返回是备份,以防您的“myMessageCell”出队失败。在这种情况下,它将显示一个空单元格而不是崩溃。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2015-04-20
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多