ios – UICollectionView在水平滚动时捕捉到单元格

我知道有些人以前提过这个问题,但他们都是关于UITableViews或UIScrollViews的,我无法得到我所接受的解决方案.我想要的是在水平滚动我的UICollectionView时的捕捉效果 – 很像iOS AppStore中发生的情况. iOS 9是我的目标版本,所以请在回答之前先看看UIKit的更改.

谢谢.

解决方法

这是值得的,这是一个简单的计算,我用( swift):
func snapToNearestCell(scrollView: UIScrollView) {

    //pick first cell to get width
    let indexPath = NSIndexPath(forItem: 0,inSection: 0)
    if let cell = collectionView.cellForItemAtIndexPath(indexPath) as UICollectionViewCell? {            
        let cellWidth = cell.bounds.size.width

        for i in 0..<collectionView.numberOfItemsInSection(0) {
            if scrollView.contentOffset.x <= CGFloat(i) * cellWidth + cellWidth / 2 {
                let indexPath = NSIndexPath(forItem: i,inSection: 0)
                collectionView.scrollToItemAtIndexPath(indexPath,atScrollPosition: .CenteredHorizontally,animated: true)
                break
            }
        }
    }
}

呼叫你需要的地方我叫它

func scrollViewDidEndDragging(scrollView: UIScrollView,willDecelerate decelerate: Bool) {
    snapToNearestCell(scrollView)
}

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
    snapToNearestCell(scrollView)
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...