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

5
我正在尝试从一个视图控制器传递一个数字(页面编号)到另一个启用“分页”的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)
}

结果:

enter image description here

我需要的:

enter image description here

解决方案:

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)

    }
1个回答

2
您可以尝试这样滚动:
collectionView.setContentOffset(CGPoint(x:  currentPage * itemSize, y: 0), animated: false)

其中itemSize是集合视图中项目的大小。如果每个项目之间有间距,计算x时也需要将其添加。

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


你需要使用 itemSize.width,如果需要将 currentPage 强制转换为 CGFloat,可以像这样写 CGFloat(currentPage) - anho
1
谢谢,但是我改成了collectionView.bounds.size.width而不是itemSize,现在它可以正常工作了。 - iOS.Lover
我刚刚发现另一个问题!这行代码只适用于iPhone 4.7英寸屏幕!!!为什么?在Storyboard中选择的设备是iPhone 7,但我添加了约束。那么为什么会出现这种情况? - iOS.Lover
1
只有当您的项目大小恒定时,才能像您说的那样正常工作...如果您希望该项目在所有设备上都具有全宽度,则需要在“UICollectionViewDelegateFlowLayout”函数中创建它,因此对于您的项目来说,一个很好的尺寸将是 return CGSize(width: view.bounds.width, height: 150),这将具有动态宽度(取决于屏幕大小)和静态高度。 - anho
不应该为 width 使用常量。 - anho
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接