水平滚动UICollectionView时,捕捉到单元格的中心 [英] Snap to center of a cell when scrolling UICollectionView horizontally

查看:85
本文介绍了水平滚动UICollectionView时,捕捉到单元格的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有些人之前曾问过这个问题,但是他们都是关于UITableViewsUIScrollViews的,所以我无法获得公认的解决方案来为我工作.我想要的是水平滚动UICollectionView时的捕捉效果-就像iOS AppStore中发生的情况一样. iOS 9+是我的目标版本,因此在回答此问题之前,请先查看UIKit的更改.

I know some people have asked this question before but they were all about UITableViews or UIScrollViews and I couldn't get the accepted solution to work for me. What I would like is the snapping effect when scrolling through my UICollectionView horizontally - much like what happens in the iOS AppStore. iOS 9+ is my target build so please look at the UIKit changes before answering this.

谢谢.

推荐答案

虽然我最初使用的是Objective-C,但后来我切换到了Swift,因此最初接受的答案还不够.

While originally I was using Objective-C, I since switched so Swift and the original accepted answer did not suffice.

我最终创建了一个UICollectionViewLayout子类,该子类提供了最佳(imo)体验,而其他功能则在用户停止滚动时会更改内容偏移量或类似内容.

I ended up creating a UICollectionViewLayout subclass which provides the best (imo) experience as opposed to the other functions which alter content offset or something similar when the user has stopped scrolling.

class SnappingCollectionViewLayout: UICollectionViewFlowLayout {

    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        guard let collectionView = collectionView else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) }

        var offsetAdjustment = CGFloat.greatestFiniteMagnitude
        let horizontalOffset = proposedContentOffset.x + collectionView.contentInset.left

        let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)

        let layoutAttributesArray = super.layoutAttributesForElements(in: targetRect)

        layoutAttributesArray?.forEach({ (layoutAttributes) in
            let itemOffset = layoutAttributes.frame.origin.x
            if fabsf(Float(itemOffset - horizontalOffset)) < fabsf(Float(offsetAdjustment)) {
                offsetAdjustment = itemOffset - horizontalOffset
            }
        })

        return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
    }
}

对于当前布局子类的最原始的感觉减速度,请确保设置以下内容:

For the most native feeling deceleration with the current layout subclass, make sure to set the following:

collectionView?.decelerationRate = UIScrollViewDecelerationRateFast

这篇关于水平滚动UICollectionView时,捕捉到单元格的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆