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

tableView.reloadData在tableViewDidSelect中未调用代理和数据源方法问题

解决tableViewDidSelect中reloadData后代理方法未触发的问题

看起来你在实现条款展开/收起的交互时遇到了代理方法不调用的问题,我来帮你一步步排查和解决:

首先检查数据源方法的核心逻辑

代理方法(比如tableView(_:cellForRowAt:)、tableView(_:heightForRowAt:))不触发最常见的原因是表格行数没有根据isTermAndConditionExpanded的状态动态更新。你必须确保numberOfRowsInSection方法里根据这个布尔值返回正确的行数:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // 展开时显示2行(标题行+内容行),收起时只显示1行标题
    return isTermAndConditionExpanded ? 2 : 1
}

如果这里没有动态调整行数,reloadData之后表格的行数没有变化,系统就不会触发相关代理方法去刷新单元格。

调整scrollToRow的执行时序

tableView.reloadData()的刷新操作是在下一次RunLoop周期完成的,属于异步执行逻辑。如果在它之后立刻调用scrollToRow,可能会出现表格还没完成刷新就执行滚动的情况,甚至可能导致崩溃(比如收起时行数变为1,却尝试滚动到row=1)。你可以用CATransaction来监听刷新完成,再执行滚动:

if indexPath.row == 0 { 
    isTermAndConditionExpanded = !isTermAndConditionExpanded 
    
    // 用CATransaction包裹,确保滚动在刷新完成后执行
    CATransaction.begin()
    CATransaction.setCompletionBlock {
        let targetIndexPath = self.isTermAndConditionExpanded 
            ? IndexPath(row: 1, section: indexPath.section) 
            : IndexPath(row: 0, section: indexPath.section)
        self.tableView.scrollToRow(at: targetIndexPath, at: .bottom, animated: true)
    }
    tableView.reloadData()
    CATransaction.commit()
}

额外确认点

  • 检查你的ViewController是否在viewDidLoad里正确设置了tableView的delegate和dataSource(比如tableView.delegate = self、tableView.dataSource = self);
  • 如果表格包含多个section,要确保numberOfRowsInSection的逻辑只针对目标section生效,避免影响其他section的行数。

按照上面的步骤调整后,代理方法应该能正常触发,展开/收起的滚动逻辑也会更稳定。

内容的提问来源于stack exchange,提问作者Abhishek Kashyap

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:29:15