【发布时间】:2020-07-19 16:40:30
【问题描述】:
我正在尝试创建一个视图,在启用了水平滚动和分页的情况下,在一行中显示所有工作日的日期。与它在 iPhone 的日历应用程序中的工作方式类似,应该可以同时看到一整周。
为此,我创建了一个 collectionView 并将其设置为显示这七个项目。当用户向左滚动时(查看下周),函数collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) 被调用。在这里我添加下一项并重新加载collectionView。:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.item > numberofitems - 10 {
numberofitems += 15
DispatchQueue.main.async {
self.myCollectionView.reloadData()
}
}
collectionView 然后重新加载:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! myCollectionViewCell
dayComponent.day = -3 * 7 - Calendar.current.component(.weekday, from: Date()) + indexPath.item + 1 + indecesadded
cell.setup(date: Calendar.current.date(byAdding: dayComponent, to: Date())!)
}
这似乎工作得很好。
但是,我还需要的是能够向另一个方向(向后)滚动并在可见单元格之前添加新单元格。我尝试使用相同的方法并添加 contentOffset:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.item < 10 {
numberofitems += 14
indecesadded += 14
DispatchQueue.main.async {
self.myCollectionView.reloadData()
self.myyCollectionView.setContentOffset(CGPoint(x: self.myCollectionView.contentOffset.x + 2 * self.view.bounds.width, y: 0), animated: false)
}
}
}
问题是在添加新单元格(中间滚动)后,滚动突然停止。当我再次手动开始滚动时,分页似乎已关闭,这意味着一周的最后一天与下一天的第一天不对应 - 1。(见下图)。
所以问题是:如何在启用分页的情况下在 collectionView 中当前存在的单元格之前插入项目,而不会弄乱滚动和分页?
【问题讨论】:
标签: ios swift uitableview uicollectionview uiscrollview