【问题标题】:How do I programmatically add cell style to a cell using tableView.dequeueReusableCell?如何使用 tableView.dequeueReusableCell 以编程方式将单元格样式添加到单元格?
【发布时间】:2022-01-04 20:45:37
【问题描述】:

我正在做一个程序化的 Swift 应用程序,但在使用 tableView.dequeueReusableCell 时找不到向单元格添加 style: .subtitle 的方法。

在下面的代码中,我希望能够将样式设置为 .subtitle:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
    ...
        
    return cell
}

我尝试添加以下内容,但不能与 dequeue 结合使用:

var cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

添加这个的正确方法是什么?

【问题讨论】:

    标签: swift uitableview


    【解决方案1】:

    子类UITableViewCell,并覆盖init(style:reuseIdentifier:)

    class MyTableViewCell: UITableViewCell {
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
        }
    }
    

    然后,用表格视图注册这个类:

    tableView.register(MyTableViewCell.self, forCellReuseIdentifier: "cellIdentifier")
    

    【讨论】:

      猜你喜欢
      • 2015-04-27
      • 1970-01-01
      • 2020-10-18
      • 2014-10-16
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多