UICollectionView在选中单元格时滚动。

35

当我尝试在 UICollectionView 中选择一个项目时,遇到了麻烦,因为当我点击它时,它会滚动一点。

我知道didSelectItemAtIndexPath被调用了,但我想在选择时防止滚动。我只希望在用户滚动时才滚动集合视图,但如果用户只是轻按单元格,它不应该移动。应该只是被选中。

希望你能帮助我,因为我不知道如何解决这个问题。

任何帮助将非常感激。


请问你能分享一下你的代码吗? - user3432164
当在collectionView中使用列表布局时,使用与在UITableView中所做的功能等效的代码时,也会发生这种情况。 - MH175
6个回答

105

如果你使用编程方式通过collectionview.selectItem(at: indexpath, animated:true, scrollPosition:.top)来选择单元格--既然你没有与我们分享任何代码,那么让我们假设这是正确的...

...那么就像我一样,你可能没有意识到可以使用空集合,例如:collectionview.selectItem(at: indexpath, animated: true, scrollPosition: [])


这太可怕了,自从什么时候[.foo].foo成为指定OptionSet的等效方式了?! - Robert Atkins

11

如果启用了分页并且手动滚动CollectionView到与预期页面边界不对齐的位置,就会发生这种情况。当您选择单元格时,它将进行调整以使CollectionView处于正确的页面边界。


1
嗨@CodeSmith,这个帮助了我两年后,但是我想在我的scrollView上保持分页行为。你有成功地同时实现了它们吗? - Edouard Barbier
我认为我的解决方法是实现一个自定义的UICollectionViewLayout,并使页面大小正确地适应屏幕。页面有几个像素偏差,而布局修复了尺寸问题。 - CodeSmith

5
在Swift 5中,你可以这样做
let indexPath = IndexPath(item: 10, section: 0)

self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .none)

在 `viewDidAppear` 或者 `viewDidLayoutSubviews` 方法中

3
您可以尝试以下方法:
collectionView.selectItem(at: newIdexPath, animated: true, scrollPosition: UICollectionViewScrollPosition(rawValue: 0))

1
在我的情况下,我通过定义自定义的UICollectionViewFlowLayout来解决了这个问题。
    private var flowLayout: UICollectionViewFlowLayout {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
        flowLayout.scrollDirection = UICollectionView.ScrollDirection.horizontal
        flowLayout.minimumInteritemSpacing = 15
        return flowLayout
    }

并将其分配给collectionView

collectionView.collectionViewLayout = flowLayout


-3

Swift 5

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接