滚动到 UICollectionView 中启用分页的页面

Mc.*_*ver 5 iphone xcode ios uicollectionview swift

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

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)
}
Run Code Online (Sandbox Code Playgroud)

结果 :

在此输入图像描述

我需要的 :

在此输入图像描述

解决方案 :

collectionView.setContentOffset(CGPoint(x:  CGFloat(currentPage) * collectionView.bounds.size.width , y: 0), animated: false)
Run Code Online (Sandbox Code Playgroud)

编辑

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

        return CGSize(width: 321 , height: 321)

    }
Run Code Online (Sandbox Code Playgroud)

anh*_*nho 2

你可以尝试像这样滚动:

collectionView.setContentOffset(CGPoint(x:  currentPage * itemSize, y: 0), animated: false)
Run Code Online (Sandbox Code Playgroud)

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

编辑:您需要使用itemSize.width,以防万一您需要将 currentPage 强制转换为CGFloat这样CGFloat(currentPage)