swift - 滚动 TableView (Swift) 时单元格消失
问题描述
我对 Swift 很陌生,有点困惑。我已经对我的 Firestore 进行了编程,以将数据加载到 TableView 中。但是,当我在 tableView 中滚动加载数据时,tableView 中的单元格消失了。我已经复制了逻辑下面的代码,想知道是否有人知道为什么代码单元会消失?
我看到其他人问过这个问题,但是当我使用他们的建议时运气不佳。谢谢!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(indexPath.row > myRatingsRestaurant.count-1){
return UITableViewCell()
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyRatingsViewCell", for: indexPath) as! MyRatingsViewCell
cell.tag = indexPath.row
let myRatingRestaurant = myRatingsRestaurant[indexPath.row] //Thread 1: Fatal error: Index out of range
cell.set(myRatingRestaurant: myRatingRestaurant)
return cell
}
}
解决方案
根据 Apple文档,只有在屏幕上显示单元格时才会加载它们以提高性能,并仅在需要时分配内存。cellForRow
当它们滚动到时加载单元格。
下面这个逻辑有些不对劲。
if(indexPath.row > myRatingsRestaurant.count-1) {
return UITableViewCell()
}
假设您的表格视图中有 10 个项目。一旦滚动到indexPath
row
10。此逻辑indexPath.row > myRatingsRestaurant.count - 1
变为真并返回一个空单元格。当您向下滚动到表格视图的末尾时,这些数据点不应该返回一个空的表格视图单元格。
假设您符合 UITableView 协议numberOfRowsInSection
应该处理要在表格视图中加载的项目数,并且不需要此逻辑。
推荐阅读
- r - 如何根据不同的分组在 R 中制作和组织均值和 sds 表
- javascript - 延迟更新计算值,直到设置了某些所需状态
- html - 带有弹性框的 HTML 模板
- python - 将其从 DataFram 转换为 List 后 Col 丢失
- azure-functions - 解决方案中的多个 Azure 功能项目
- excel - 将 excel 工作表转换为 .txt,在 Excel VBA 中复制的数字应不带引号“”
- javascript - nodemon 应用程序崩溃 - 在从服务器获得响应后开始错误之前等待文件更改
- javascript - 使用 html 服务器运行 Node.js 应用程序
- r - 在 Shiny 的隐藏部分取消暂停元素
- java - 检查 LocalTime 是否在 Java 范围内?