繁体   English   中英

在启用分页的情况下滚动到UICollectionView中的页面

[英]Scroll to a page in UICollectionView with paging enabled

我试图将一个数字(页码)从视图控制器传递到另一个视图控制器,该控制器具有UICollectionViewpaging enabled UICollectionView选项。 我的代码滚动到一个页面,但内容不居中,这是我的代码:

override func viewWillAppear(_ animated: Bool) {
    let currentPage = 4
    let indexPath = NSIndexPath(row: currentPage , section: 0) as IndexPath
    self.collectionView.scrollToItem(at: indexPath, at: .right, animated: true)
}

结果:

在此输入图像描述

我需要的 :

在此输入图像描述

方案:

collectionView.setContentOffset(CGPoint(x:  CGFloat(currentPage) * collectionView.bounds.size.width , y: 0), animated: false)

EDITED

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

        return CGSize(width: 321 , height: 321)

    }

您可以尝试像这样滚动:

collectionView.setContentOffset(CGPoint(x:  currentPage * itemSize, y: 0), animated: false)

其中itemSize是集合视图中项目的大小。 此外,如果每个项目之间有间距,则在计算x时也应添加该项目

编辑:你需要使用itemSize.width ,如果你需要像这样CGFloat(currentPage)将currentPage转换为CGFloat

暂无
暂无

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

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