Swift 4:给仅含一行静态行的TableView分区插入数组行报错问题
问题分析与解决方案
你的报错核心原因很明确:你只告诉TableView插入1行,但你的numberOfRowsInSection返回的是增加3行后的总数(1+3=4),系统预期的行数变化是1→4(+3行),但你只插入了1行,导致行数不匹配。
为什么会出现这个问题?
初始状态下,目标分区只有1行(row 0)。当你要展示3条评论时,需要在这个分区里新增3行(row 1、row 2、row 3),而不是只插入1行。你当前的代码只创建了一个IndexPath(row: 3, section: path.section),这相当于只插入了最后一行,系统自然会认为行数变化是1→2,和你numberOfRowsInSection返回的4行矛盾,从而抛出错误。
修复步骤
- 生成所有需要插入的IndexPath数组:遍历需要新增的行数,创建对应的IndexPath集合
- 优化可选值处理:避免强制解包
comments?.count,防止空值崩溃 - 确保插入行数与
numberOfRowsInSection返回值匹配
修改后的代码
首先更新showComments函数:
func showComments(model: MGPostModel, sender: MGCommunityPostTableViewCell) { guard let path = self.communityTableView.indexPath(for: sender), let commentsCount = model.comments?.count, commentsCount > 0 else { return } print(path) print(commentsCount) self.currentSection = path.section // 生成所有需要插入的IndexPath:从row 1开始,一共commentsCount行 var indexPathsToInsert = [IndexPath]() for row in 1..<(1 + commentsCount) { indexPathsToInsert.append(IndexPath(row: row, section: path.section)) } print(indexPathsToInsert) self.communityTableView.beginUpdates() self.communityTableView.insertRows(at: indexPathsToInsert, with: .automatic) self.communityTableView.endUpdates() }
然后优化numberOfRowsInSection的可选值处理,减少崩溃风险:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let postModel = self.postsArray[section] let commentsCount = postModel.comments?.count ?? 0 if self.currentSection == section { return 1 + commentsCount } else { print("nie rozszerzone") return 1 } }
额外提示
如果需要支持再次点击按钮收起评论,你可以在showComments里判断当前分区是否已经展开:如果已经展开,就删除对应的行,并将currentSection设置为一个无效值(比如-1),同时更新numberOfRowsInSection的逻辑即可。
内容的提问来源于stack exchange,提问作者kajz3reczka
相关产品推荐
相关产品推荐

