UICollectionView Cell滚动到中心

问题描述 投票:10回答:5

我在我的UIViewController中使用UICollectionView。

我的collectionview属性设置如下。

现在我希望滚动后单元格在屏幕上居中!选项1:

选项2:

我需要做什么来实现选项2?

更新:

最后我使用下面的代码作为滚动与其他答案不顺利。

  - (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{    CGFloat offsetAdjustment = MAXFLOAT;
    CGFloat horizontalCenter = proposedContentOffset.x + (CGRectGetWidth(self.collectionView.bounds) / 2.0);

    CGRect targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
    NSArray* array = [super layoutAttributesForElementsInRect:targetRect];

    for (UICollectionViewLayoutAttributes* layoutAttributes in array) {
        CGFloat itemHorizontalCenter = layoutAttributes.center.x;

        if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offsetAdjustment)) {
            offsetAdjustment = itemHorizontalCenter - horizontalCenter;
        }
    }    
    return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y);
}
ios objective-c uicollectionviewcell uicollectionviewlayout
5个回答
15
投票

你可以在你的targetContentOffsetForProposedContentOffset:withScrollingVelocity:子类中覆盖UICollectionViewLayout方法,并像这样计算你的偏移量:

@property (nonatomic, assign) CGFloat previousOffset;
@property (nonatomic, assign) NSInteger currentPage;

...

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
    NSInteger itemsCount = [self.collectionView.dataSource collectionView:self.collectionView numberOfItemsInSection:0];

    // Imitating paging behaviour
    // Check previous offset and scroll direction
    if ((self.previousOffset > self.collectionView.contentOffset.x) && (velocity.x < 0.0f)) {
        self.currentPage = MAX(self.currentPage - 1, 0);
    } else if ((self.previousOffset < self.collectionView.contentOffset.x) && (velocity.x > 0.0f)) {
        self.currentPage = MIN(self.currentPage + 1, itemsCount - 1);
    }

    // Update offset by using item size + spacing
    CGFloat updatedOffset = (self.itemSize.width + self.minimumInteritemSpacing) * self.currentPage;
    self.previousOffset = updatedOffset;

    return CGPointMake(updatedOffset, proposedContentOffset.y);
}

编辑:感谢您指出这一点,忘了说您必须先禁用分页:

self.collectionView.pagingEnabled = NO;

更新:附加Swift 4.2版本

...
collectionView.isPagingEnabled = false
...

class YourCollectionLayoutSubclass: UICollectionViewFlowLayout {

    private var previousOffset: CGFloat = 0
    private var currentPage: Int = 0

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

        let itemsCount = collectionView.numberOfItems(inSection: 0)

        // Imitating paging behaviour
        // Check previous offset and scroll direction
        if previousOffset > collectionView.contentOffset.x && velocity.x < 0 {
            currentPage = max(currentPage - 1, 0)
        } else if previousOffset < collectionView.contentOffset.x && velocity.x > 0 {
            currentPage = min(currentPage + 1, itemsCount - 1)
        }

        // Update offset by using item size + spacing
        let updatedOffset = (itemSize.width + minimumInteritemSpacing) * CGFloat(currentPage)
        previousOffset = updatedOffset

        return CGPoint(x: updatedOffset, y: proposedContentOffset.y)
    }
}

9
投票

你可以使用代码self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)


6
投票

这是@ dmitry-zhukov的Swift 3版本(谢谢顺便说一句!)

class PagedCollectionLayout : UICollectionViewFlowLayout {

    var previousOffset : CGFloat = 0
    var currentPage : CGFloat = 0

    override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {

        let sup = super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)

        guard
            let validCollection = collectionView,
            let dataSource = validCollection.dataSource
            else { return sup }

        let itemsCount = dataSource.collectionView(validCollection, numberOfItemsInSection: 0)

        // Imitating paging behaviour
        // Check previous offset and scroll direction
        if  (previousOffset > validCollection.contentOffset.x) && (velocity.x < 0) {
            currentPage = max(currentPage - 1, 0)
        }
        else if (previousOffset < validCollection.contentOffset.x) && (velocity.x > 0) {
            currentPage = min(currentPage + 1, CGFloat(itemsCount - 1))
        }

        // Update offset by using item size + spacing
        let updatedOffset = ((itemSize.width + minimumInteritemSpacing) * currentPage)
        self.previousOffset = updatedOffset

        let updatedPoint = CGPoint(x: updatedOffset, y: proposedContentOffset.y)

        return updatedPoint
    }
}

1
投票

我找到了很多信息和解决方案。

现在,我用这个。

在UICollectionViewFlowLayout覆盖:

override public func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {

    if display != .inline {
        return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
    }

    guard let collectionView = collectionView else {
        return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
    }

    let willtoNextX: CGFloat

    if proposedContentOffset.x <= 0 || collectionView.contentOffset == proposedContentOffset {
        willtoNextX = proposedContentOffset.x
    } else {

        let width = collectionView.bounds.size.width
        willtoNextX = collectionView.contentOffset.x + (velocity.x > 0 ?  width : -width)
    }

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

    var offsetAdjustCoefficient = CGFloat.greatestFiniteMagnitude

    let horizontalOffset = proposedContentOffset.x + collectionView.contentInset.left

    let layoutAttributesArray = super.layoutAttributesForElements(in: targetRect)

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

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

并在UICollectionViewController上:

collectionView.decelerationRate = .fast
collectionView.isPagingEnabled = false
collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: 16)

现在,细胞在中心!!

preview


0
投票

我不知道为什么每个人的答案都是如此复杂,我只需在Interface Builder中打开Paging enabled就可以了。


0
投票

设置适当的itemSizeleftright插入后,我更喜欢这样做而不是子类化布局

//Setting decelerationRate to fast gives a nice experience
collectionView.decelerationRate = .fast

//Add this to your view anywhere
func centerCell () {
    let centerPoint = CGPoint(x: collectionView.contentOffset.x + collectionView.frame.midX, y: 100)
    if let path = collectionView.indexPathForItem(at: centerPoint) {
        collectionView.scrollToItem(at: path, at: .centeredHorizontally, animated: true)
    }
}

//Set collectionView.delegate = self then add below funcs
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
   centerCell()
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
    centerCell()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if !decelerate {
        centerCell()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.