【问题标题】:Is it possible to store custom UITableViewCell into Array?是否可以将自定义 UITableViewCell 存储到数组中?
【发布时间】:2019-03-11 00:31:37
【问题描述】:

我有很多自定义单元格,并希望通过使用结构并将有关单元格的信息存储在数组中来简化 cellForRowAt

struct HowToCells {
    let helpCell: UITableViewCell
    let identifier: String
    let icon: UIImage
    let cellName: String
}

var cellArray = [HowToCells]()

cellArray.append(HowToCells.init(helpCell: ScreenRecordingTableViewCell(), identifier: "ScreenRecordingTableViewCell", icon: HowToImage.screenRecording.image(), cellName: "Enable screen recording"))

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

     let c = cellArray[indexPath.row]
     let cellToUse = c.helpCell

     let cell = tableView.dequeueReusableCell(withIdentifier: c.identifier, for: indexPath) as! cellToUse

}

我收到以下错误:使用未声明的类型“cellToUse”

ScreenRecordingTableViewCell 是一个自定义的 UITableViewCell

【问题讨论】:

  • 这正是引入重用单元的原因:将不可见的单元保持在内存中......
  • “想通过使用结构体来简化 cellForRowAt 并将有关单元格的信息存储在数组中。” 然后将信息存储在数组中,而不是单元格本身,这顺便说一句,你必须做任何事情才能让桌子工作!
  • @RakeshaShastri - ScreenRecordingTableViewCell 在这种情况下是实际的单元格,它被存储在数组中。

标签: swift uitableview cell subclass


【解决方案1】:

您在此行收到错误: 让 cell = tableView.dequeueReusableCell(withIdentifier: c.identifier, for: indexPath) as!细胞使用

因为应该在 as! 之后使用 UITableViewCell 子类类型,而不是变量名。 x作为! y 要求强制将对象 X 的类型转换为类型 Y。

话虽如此,您会遇到在数组中存储单元格和使用 tableView.dequeueReusableCell 的问题,它获取现有单元格,将其出列然后重新使用它。这会损坏您的数据。您需要将单元格的所有数据放入数组中,然后从 cellForRow 中的数组中检索该索引。

【讨论】:

  • Apple 有没有建议我们不应该存储 UITableViewCells?
  • @ReDetection。是的,cell 是可取消队列的,这意味着 iOS 管理它们的生命周期,应用程序应避免使用 uitableview 数据源和委托方法与它们交互。专注于管理视图层(单元格)显示的数据,而不是单元格本身
  • 我的意思是你有一个到 developer.apple.com 的链接,其中明确指出应该避免弄乱细胞?我相信如果我不使用dequeueReusableCell 方法而是提前创建我的单元格(数量非常有限,创建后不会更改),我可以安全地将它们存储在数组中。
【解决方案2】:

您不需要将表格视图单元格存储在数组中,因为 UITableView 会自行创建和存储它们。只需在tableView(_:cellForRowAt:) 中使用tableView.dequeueReusableCell(withIdentifier:for:) 方法即可获得所需的单元格。之后,您可以配置此单元格。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CellClass
// Configure cell
return cell
}

【讨论】:

    猜你喜欢
    • 2016-09-17
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多