UICollectionView 设置默认位置

UICollectionView set default position


我有一个包含 3 个单元格的 CollectionView,它们横跨整个设备的屏幕,基本上代表了我的 3 个主要视图。
我启用了分页功能,所以它现在基本上与 iOS 主屏幕完全一样。
我的问题是我希望此 CollectionView 的 "default" 位置等于 view.frame.width,以便第二个 Cell 是 "default" 视图,我可以左右滑动以到达我的辅助视图意见。
我已经通过

尝试过
collectionView.scrollToItem()

collectionView.scrollRectToVisible()

以及

collectionView.setContentOffset()

但它们似乎都只有在加载视图后才能工作(我通过导航栏中的按钮尝试了它们)。 提前谢谢你!


编辑:
现在这可行了,但我在那个中间单元格中还有另一个集合视图,它包含一个小的 2 页 UICollectionView 列表,它们实际上是来自 UICollectionViewCell 的子 class 的对象,称为PersonCell每人持有一个UICollectionView。我也希望将这些 UICollectionViews 滚动到索引 1,这是我的代码:

for tabcell in (collectionView?.visibleCells)! {
    if let maincell: MainCell = tabcell as? MainCell {
        for cell in maincell.collectionView.visibleCells {
            if let c = cell as? PersonCell {
                c.collectionView.scrollToItem(at: (NSIndexPath(item: 1, section: 0) as IndexPath), at: [], animated: false)
            }
        }
    }
}

这是在我的'root'CollectionViewControllerviewDidLayoutSubviews中执行的。



编辑 2: 现在我尝试在 MainCell class 中使用以下代码(这是一个 UICollectionViewCell subclass):

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    let personCell = cell as! PersonCell
    personCell.collectionView.scrollToItem(at: (NSIndexPath(item: 1, section: 0) as IndexPath), at: [], animated: false)
}



编辑 3:
长话短说,我基本上需要一个委托方法,在 一个单元格添加到 UICollectionView.

之后调用

你试过了吗[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

尝试调用 viewDidLayoutSubviews

中的代码

好的,我知道了!
这个 SO 回答给了我最后的提示:

基本上,现在我只是在 Cell 初始化后执行此操作:

self.collectionView.alpha = 1
self.data = data // array is filled with data
self.collectionView.reloadData()
DispatchQueue.main.async {
    for cell in self.collectionView.visibleCells {
        (cell as! PersonCell).collectionView.scrollToItem(at: (NSIndexPath(item: 1, section: 0) as IndexPath), at: [], animated: false)
    }
    self.collectionView.alpha = 1
}

基本上,DispatchQueue.main.async{...} 中的代码在下一个 UI 刷新周期中被调用,这意味着单元格已经存在。为了防止用户在几分之一秒内看到错误的页面,我将整个 collectionView 的 alpha 设置为 0,并在数据存在、单元格存在并且页面滚动时立即切换它。