我正在尝试从一个视图控制器传递一个数字(页面编号)到另一个启用“分页”的
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)
已编辑
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 321 , height: 321)
}
itemSize.width
,如果需要将currentPage
强制转换为CGFloat
,可以像这样写CGFloat(currentPage)
。 - anhocollectionView.bounds.size.width
而不是itemSize
,现在它可以正常工作了。 - iOS.Loverreturn CGSize(width: view.bounds.width, height: 150)
,这将具有动态宽度(取决于屏幕大小)和静态高度。 - anhowidth
使用常量。 - anho