You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

可复用Cell与ViewModel协作原理及相关技术疑问

关于UITableView复用Cell的疑问解答

疑问1:复用Cell如何对应正确的ViewModel?

Cell不需要“记住”对应的ViewModel。每次tableView(_:cellForRowAt:)方法触发时,你都会根据当前indexPath从排序后的dummyViewModels数组中取出对应ViewModel,调用cell.config()重新配置Cell内容。无论这个Cell之前展示过哪个位置的数据,重新配置都会覆盖旧内容,因此最终始终展示当前indexPath对应的正确数据。

疑问2:传入引用类型ViewModel会导致Cell不复用吗?

不会。UITableView的Cell复用由系统管理,只要你调用dequeueReusableCell(withIdentifier:for:),系统就会自动复用Cell——只会创建屏幕可见范围内所需数量的Cell(通常远少于30个),当Cell滑出屏幕时会被放入复用池,新内容滑入时再从池中取出重新配置。ViewModel是引用类型还是值类型,和Cell是否复用毫无关系,它只是给Cell提供数据的载体而已。

代码合理性分析

你的代码完全符合UITableView复用Cell的规则,逻辑正确:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    Constant.dummyViewModels.count
}

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

    cell.config(Constant.dummyViewModels[indexPath.row])

    return cell
}

每次复用Cell时都会重新绑定对应位置的ViewModel,确保了展示数据的准确性。

内容的提问来源于stack exchange,提问作者Steven-Carrot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:25:16