【问题标题】:UICollectioView: wrong content offset after adding cellsUICollectionView:添加单元格后内容偏移错误
【发布时间】:2016-08-11 12:14:03
【问题描述】:

我创建了循环 UICollectionView(因此用户不可能滚动到最后,因为当他滚动到上一行时,我从末尾删除了不正确的行以将它们插入到 UICollectionView 的开头。

在我的 UICollectioView 中,我总是有 11 个单元格。 UICollectionViewCell 与 UICollectionView 具有相同的边界。

问题:例如,我将内容滚动到行 = 2 的 indexPath。如果我在开头添加 2 个单元格并从末尾删除 2 个单元格,我希望看到相同的单元格,但它滚动到第二行(我之前看到的行),但我不想滚动,我想插入 2 行没有任何动画,所以用户应该看到第 4 行,但它认为它是第二行)

代码如下:

let numberOfRowInCollectionView = collectionView_help_getNumberOfRowsInCollectionView()
                collectionViewMain.performBatchUpdates({ [weak self] in

                    if self == nil {
                        return
                    }

                    let currentRowOffset = 2
                    let numberOfRowsToAddFromLeft = currentRowOffset // number of rows we need to add or remove from left
                    var array_indexPathToAdd = [NSIndexPath]()
                    var array_indexPathToRemove = [NSIndexPath]()
                    for i in 0..<numberOfRowsToAddFromLeft {
                            array_indexPathToAdd.append(NSIndexPath(forRow: i, inSection: 0))
                            array_indexPathToRemove.append(NSIndexPath(forRow: numberOfRowInCollectionView - 1 - i, inSection: 0))
                        }

                    self?.collectionViewMain.insertItemsAtIndexPaths(array_indexPathToAdd)
                    self?.collectionViewMain.deleteItemsAtIndexPaths(array_indexPathToRemove)

                    self!.selectedRow += currentRowOffset

                    }, completion: {  (finished) in
                        completionBlock?()
                })

我尝试添加:

// select new row
                        let selectedIndexPath = NSIndexPath(forRow: self!.selectedRow, inSection: 0)
                        self!.collectionViewMain.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: .CenteredHorizontally, animated: false)

然后它会选择适当的新行(现在它 = 4),但它会使用动画来完成,因此用户会看到正在发生的事情。

但我只想在开头添加 2 个单元格,用户不应该看到这种情况正在发生。

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout


    【解决方案1】:

    我用这个源码实现了这个循环UICollectionViewGit

    这个想法不是在 UICollectionView 中使用删除和插入单元格,而只是有额外的 0(包含数组中最后一个对象的数据)和最后一行(包含数组中 0 个对象的数据)行,并设置内容偏移量而无需动画。

    【讨论】:

      猜你喜欢
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 2013-11-21
      相关资源
      最近更新 更多