如何改变 cell 的 UITableViewCellStyle 属性并复用 cell

一般地,我们对 cell 进行复用会采用如下代码:

// 在 viewDidLoad 方法中注册
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

...

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

但这样做的结果是 cell 的 UITableViewCellStyle 属性是默认的 default。而 UITableViewCellStyle 只能在如下初始化方法中设置:

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

那该如何改变 UITableViewCellStyle 且同时达到复用的目的呢?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell: UITableViewCell? = nil
        cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        if cell == nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
        }
        return cell!
    }

Ref:
https://blog.csdn.net/weixin_42349140/article/details/80947266
http://www.cocoachina.com/bbs/read.php?tid-1730647.html
http://www.cocoachina.com/bbs/read.php?tid-1706470.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容