简体   繁体   English

选择单元格时 UICollectionView 正在滚动

[英]UICollectionView is scrolling when selecting a cell

I'm having trouble when i try to select an item inside a UICollectionView since when I click on it it scrolls a little bit.当我尝试在UICollectionView中选择一个项目时遇到问题,因为当我单击它时它会滚动一点。

I know didSelectItemAtIndexPath is being called but I want to prevent the scrolling when selecting.我知道didSelectItemAtIndexPath正在被调用,但我想在选择时阻止滚动。 I only want the collection view to scroll when the user is scrolling through but if the user is just tapping the cell it shouldn't move.我只希望在用户滚动时滚动集合视图,但如果用户只是点击单元格,它不应该移动。 Only should be selected.只应选择。

I hope you can help me since I don't know how to prevent this problem.我希望你能帮助我,因为我不知道如何防止这个问题。

Any help will be really appreciated.任何帮助将不胜感激。

If you are selecting the cell programmatically with collectionview.selectItem(at: indexpath, animated: true, scrollPosition: .top) -- and since you didn't share any of your code with us, let's assume that's correct...如果您使用collectionview.selectItem(at: indexpath, animated: true, scrollPosition: .top)编程方式选择单元格 - 并且由于您没有与我们共享任何代码,我们假设这是正确的...

... then like me you might not have realized that you can use an empty set like this: collectionview.selectItem(at: indexpath, animated: true, scrollPosition: []) ...然后像我一样你可能没有意识到你可以使用这样的空集: collectionview.selectItem(at: indexpath, animated: true, scrollPosition: [])

This can happen if you have paging enabled and the CollectionView is manually scrolled to a position that doesn't align with the expected page boundaries.如果您启用了分页并且 CollectionView 被手动滚动到与预期页面边界不对齐的位置,则可能会发生这种情况。 When you select the cell, it adjusts to put the CollectionView at the correct page boundaries.当您选择单元格时,它会进行调整以将 CollectionView 置于正确的页面边界。

你可以试试这个:

collectionView.selectItem(at: newIdexPath, animated: true, scrollPosition: UICollectionViewScrollPosition(rawValue: 0))

In Swift 5 you can do在 Swift 5 中你可以做到

let indexPath = IndexPath(item: 10, section: 0)

self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .init(rawValue: 0))

in viewDidAppear or viewDidLayoutSubviewsviewDidAppearviewDidLayoutSubviews

collectionView.selectItem(at: indexPath, animated: false, scrollPosition: [])

For Objective-C 对于Objective-C

[self.collectionView selectItemAtIndexPath:path animated:NO scrollPosition:UICollectionViewScrollPositionNone] 

For Swift 对于斯威夫特

collectionview.selectItemAtIndexPath(indexPath: path, animated: false, scrollPosition: None)

swift 5迅捷 5

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM