ios - 加载 UICollectionView 的 N 个视图并在最后重新加载
问题描述
[回复后编辑:问题末尾的解决方案]
我有一个 UICollectionView 我最初加载 4 个视图。我希望当用户滚动到最后一个(第 4 个视图)并尝试再次滚动时,我更新模型的数据,重新加载 UICollectionView 并移回第一个视图,以便用户可以再次滚动 3 次直到第四视图等。
问题是,当我最初加载 4 个视图时,用户在到达最后一个视图后无法滚动,因为之后什么都没有。所以我创建了一个空单元格作为我的第 5 个视图,现在我在初始 UICollectionView 中加载了 5 个视图。但是这第五个视图永远不会完全显示,我使用“willDisplay”方法重新加载数据并强制移回第一个视图。这并不优雅,但我找不到另一种方法。
此方法工作正常,但问题出在:似乎在调用 willDisplay 时,我确实重新加载数据并移回第一个视图,但只有这样才考虑到应该将我带到第 5 个视图的滚动这意味着在我移回第一个视图后,该应用程序实际上向我显示了第二个视图(它确实移回了第一个视图,但随后应用了我开始从第 4 个视图转到第 5 个视图的滚动,将我移动到第二视图)。
我希望这很清楚...
所以这是我正在使用的代码:
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
// if this is the last view
if((indexPath.row == self.dataModel.getNumberOfData()) && self.dataModel.getNumberOfData() > 0)
{
// I update the model here
self.dataModel.resetData()
// Then I reload the UICollectionView
self.collectionView.reloadData()
// Then I move back to the first view
self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: .centeredHorizontally)
}
}
当然,如果您有另一个更优雅的解决方案来避免第 5 种观点,我很乐意考虑。我的数据不是静态的,所以当我需要重新加载新数据时,我会查询数据库以检索新信息,因此在运行应用程序时我不知道新数据。
谢谢。
[编辑使用 scrollViewDidScroll 的解决方案。例如,我展示了如何检测结束(水平滚动并删除第一个视图......
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
// if reached the end of the UICollectionView...
if (scrollView.contentOffset.x == scrollView.contentSize.width - scrollView.frame.size.width) {
print("Reached the end...")
self.dataModel.removeNFirst(n: 1) // remove first item from model
// delete the first view of the UICollectionView
self.collectionView.performBatchUpdates({
self.collectionView.deleteItems(at: [IndexPath(item: 0, section: 0)])
}) { (finished) in
self.collectionView.reloadData()
}
}
}
解决方案
推荐阅读
- java - Raspberry pi 2 B + Selenium Java = WebDriverException: java.net.ConnectException: Failed to connect
- javascript - 使用 cron 间隔将数据保存到数据库
- java - Maven 不能使用作用域编译
- excel - 如何将带有格式的excel表格复制到word中 - 手动操作
- r - 使用 R 中的 group_by 函数按位置调用数据框的列
- google-colaboratory - 如何在 Google Colab 中导入和运行 SQL 查询?
- pandas - 在数据框中查找字符串的索引和列号
- javascript - 如何从 MongoDB 中的数组中渲染对象并做出反应
- ios - 无法从 Firebase 中注销帐户
- python - pystray 与其他代码执行