UICollectionView 水平分页不居中

UICollectionView Horizontal Paging not centered

我有一个水平滚动的 collectionView,每个单元格的大小与视图相同。当我翻阅 collectionView 时,它不会按单元格分页。单元格不在屏幕中央。我已经尝试了很多东西来尝试修复它并且没有任何运气。 这是问题的视频: https://www.youtube.com/watch?v=tXsxWelk16w 有什么想法吗?

删除项目之间的 space 秒。对于水平滚动集合视图,将最小行间距设置为 0。您可以使用界面生成器或使用 UICollectionViewDelegateFlowLayout 协议的方法来执行此操作:

- (CGFloat)collectionView:(UICollectionView *)collectionView 
                   layout:(UICollectionViewLayout *)collectionViewLayout 
        minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;    
}

另一种方法是使单元格的宽度小于 collectionView 的宽度,因为项目之间的水平值 space。然后添加部分插图,其左右插图等于项目之间水平 space 的一半。例如,您的最小行距为 10:

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
        minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (CGSize)collectionView:(UICollectionView *)collectionView 
                  layout:(UICollectionViewLayout *)collectionViewLayout 
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(collectionView.frame.size.width - 10, collectionView.frame.size.height);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView 
                        layout:(UICollectionViewLayout *)collectionViewLayout 
        insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 5, 0, 5);
}

第三种方式:在scrollViewDidEndDecelerating:方法中操作collectionView滚动:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.collectionView) {
        CGPoint currentCellOffset = self.collectionView.contentOffset;
        currentCellOffset.x += self.collectionView.frame.size.width / 2;
        NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:currentCellOffset];
        [self.collectionView scrollToItemAtIndexPath:indexPath
                                    atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                                            animated:YES];
    }
}

能够让单元格比 collectionView 框架更小,单元格之间有 space 允许向用户提示有其他单元格可以滚动到这对用户来说是一个巨大的胜利用户体验。但是页面居中并没有像预期的那样工作,随着用户滚动,每个单元格逐渐变得更加偏移。我发现以下方法效果很好。每个单元格上的 centering/snapping 动画几乎对用户不可见,因为它只是调整 collectionView 滚动自然结束的位置,而不是猛拉 collectionView 以快速滚动到另一个 indexPath .将 sectionInset 属性 设置得足够大以允许单元格不粘到包含框架的边缘仍然很重要。此外,由于单元格之间有 spaces,目标可能会落在 nil 的 indexPath 上,这会导致 collectionView 滚动回开头。我已经稍微修复了这个偏移量,然后再试一次,但这里可以采用不同的方法。

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
                 withVelocity:(CGPoint)velocity
          targetContentOffset:(inout CGPoint *)targetContentOffset
{
    //Ensure the scrollview is the collectionview we care about
    if (scrollView == self.collectionView) {

        // Find cell closest to the frame centre with reference from the targetContentOffset.
        CGPoint frameCentre = self.collectionView.center;
        CGPoint targetOffsetToCentre = CGPointMake((* targetContentOffset).x + frameCentre.x, (* targetContentOffset).y + frameCentre.y);

        NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:targetOffsetToCentre];

            //Check for "edgecase" that the target will land between cells and then find a close neighbour to prevent scrolling to index {0,0}.
        while (!indexPath) {
            targetOffsetToCentre.x += ((UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout).minimumInteritemSpacing;
            indexPath = [self.collectionView indexPathForItemAtPoint:targetOffsetToCentre];
        }

        // Find the centre of the target cell
        CGPoint centreCellPoint = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath].center;

        // Calculate the desired scrollview offset with reference to desired target cell centre.
        CGPoint desiredOffset = CGPointMake(centreCellPoint.x - frameCentre.x, centreCellPoint.y - frameCentre.y);
        *targetContentOffset = desiredOffset;
    }
}

Swift 3.0 设置自己的UICollectionViewFlowLayout

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let width = UIScreen.main.bounds.width
layout.itemSize = CGSize(width: width, height: 154)
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .horizontal
collectionView?.collectionViewLayout = layout

演示在Swift 3https://github.com/damienromito/CollectionViewCustom

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    let pageWidth = Float(itemWidth + itemSpacing)
    let targetXContentOffset = Float(targetContentOffset.pointee.x)
    let contentWidth = Float(collectionView!.contentSize.width  )
    var newPage = Float(self.pageControl.currentPage)

    if velocity.x == 0 {
        newPage = floor( (targetXContentOffset - Float(pageWidth) / 2) / Float(pageWidth)) + 1.0
    } else {
        newPage = Float(velocity.x > 0 ? self.pageControl.currentPage + 1 : self.pageControl.currentPage - 1)
        if newPage < 0 {
            newPage = 0
        }
        if (newPage > contentWidth / pageWidth) {
            newPage = ceil(contentWidth / pageWidth) - 1.0
        }
    }
    self.pageControl.currentPage = Int(newPage)
    let point = CGPoint (x: CGFloat(newPage * pageWidth), y: targetContentOffset.pointee.y)
    targetContentOffset.pointee = point
}

Swift 4:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    let pageWidth = Float(itemWidth + itemSpacing)
    let targetXContentOffset = Float(targetContentOffset.pointee.x)
    let contentWidth = Float(collectionView!.contentSize.width  )
    var newPage = Float(self.pageControl.currentPage)

    if velocity.x == 0 {
        newPage = floor( (targetXContentOffset - Float(pageWidth) / 2) / Float(pageWidth)) + 1.0
    } else {
        newPage = Float(velocity.x > 0 ? self.pageControl.currentPage + 1 : self.pageControl.currentPage - 1)
        if newPage < 0 {
            newPage = 0
        }
        if (newPage > contentWidth / pageWidth) {
            newPage = ceil(contentWidth / pageWidth) - 1.0
        }
    }

    self.pageControl.currentPage = Int(newPage)
    let point = CGPoint (x: CGFloat(newPage * pageWidth), y: targetContentOffset.pointee.y)
    targetContentOffset.pointee = point
}

在遇到类似问题后,我通过意识到使用水平滚动时高度现在是宽度而宽度现在是高度来解决我的问题,因为默认设置为垂直滚动。尝试切换值,看看是否有帮助。 https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/UsingtheFlowLayout/UsingtheFlowLayout.html

Swift 3 解决方案 基于@Santos 的回答,如果你有一个常规的水平分页集合视图 没有 像 Paolo 这样的页面控件在他的 Swift 3 示例中使用。

我用它来解决一个问题,即带有自定义 UICollectionViewFlowLayout 动画师的水平分页单元格全屏单元格没有完成旋转并最终偏移,因此全屏单元格框架的边缘越来越水平偏移滚动时从集合视图的边界(就像在视频 OP 共享中一样)。

 func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    // Ensure the scrollview is the one on the collectionView we care are working with 
    if (scrollView == self.collectionView) {
        
        // Find cell closest to the frame centre with reference from the targetContentOffset.
        let frameCenter: CGPoint = self.collectionView.center
        var targetOffsetToCenter: CGPoint = CGPoint(x: targetContentOffset.pointee.x + frameCenter.x, y: targetContentOffset.pointee.y + frameCenter.y)
        var indexPath: IndexPath? = self.collectionView.indexPathForItem(at: targetOffsetToCenter)
        
        // Check for "edge case" where the target will land right between cells and then next neighbor to prevent scrolling to index {0,0}.
        while indexPath == nil {
            targetOffsetToCenter.x += 10
            indexPath = self.collectionView.indexPathForItem(at: targetOffsetToCenter)
        }
        // safe unwrap to make sure we found a valid index path
        if let index = indexPath { 
            // Find the centre of the target cell
            if let centerCellPoint: CGPoint = collectionView.layoutAttributesForItem(at: index)?.center {
                
                // Calculate the desired scrollview offset with reference to desired target cell centre.
                let desiredOffset: CGPoint = CGPoint(x: centerCellPoint.x - frameCenter.x, y: centerCellPoint.y - frameCenter.y)
                targetContentOffset.pointee = desiredOffset
            }
        }
    }
}

Swift 3

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView == self.collectionView {
            var currentCellOffset = self.collectionView.contentOffset
            currentCellOffset.x += self.collectionView.frame.width / 2
            if let indexPath = self.collectionView.indexPathForItem(at: currentCellOffset) {
              self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
            }
        }
    }

刚刚从Apple官方指南和示例代码中看到的代码:

AssetViewController.swift:

self.collectionView?.isPagingEnabled = true
self.collectionView?.frame = view.frame.insetBy(dx: -20.0, dy: 0.0)

此代码放大了集合视图,使其延伸出屏幕,而内容恰好在屏幕边缘内

Swift @vlad-che 接受的答案版本:

extension GoodsViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {

        return 10
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let frameSize = collectionView.frame.size
        return CGSize(width: frameSize.width - 10, height: frameSize.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        return UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    }
}

Swift 4 消除行间距以保持单元格居中的解决方案:

public func collectionView(_ collectionView: UICollectionView, layout 
collectionViewLayout: UICollectionViewLayout, 
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

如果您追求 collectionView.isPagingEnabled 的行为('proper inertia feeling' 等),但在设置 contentInset 或间距时没有错误的偏移,这就是您需要的:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    let itemWidth = cellSize.width + spacing
    let inertialTargetX = targetContentOffset.pointee.x
    let offsetFromPreviousPage = (inertialTargetX + collectionView.contentInset.left).truncatingRemainder(dividingBy: itemWidth)
    
    // snap to the nearest page
    let pagedX: CGFloat
    if offsetFromPreviousPage > itemWidth / 2 {
        pagedX = inertialTargetX + (itemWidth - offsetFromPreviousPage)
    } else {
        pagedX = inertialTargetX - offsetFromPreviousPage
    }
    
    let point = CGPoint(x: pagedX, y: targetContentOffset.pointee.y)
    targetContentOffset.pointee = point
}

这里的问题是 isPagingEnabled 不考虑 contentSize,而是集合边界:

the scroll view stops on multiples of the scroll view’s bounds when the user scrolls.

为了达到我们想要的效果,我们需要自己计算下一个偏移量并关闭isPagingEnabled。

如您在上图中所见,第二个单元格应从以下位置开始:

One side + Cell - Next cell visible part.

这是一个计算的委托: https://gist.github.com/danielCarlosCE/7a5f80dc6087773ba147be4dc72da826

将集合视图添加到全屏并删除单元格之间的间距,估计大小将为 None

添加此集合视图委托方法

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(宽度: collectionView.frame.width, 高度: collectionView.frame.height) }