[英]Scroll to a page in UICollectionView with paging enabled
我试图将一个数字(页码)从视图控制器传递到另一个视图控制器,该控制器具有UICollectionView
了paging 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.