繁体   English   中英

UICollectionView设置默认位置

[英]UICollectionView set default position


我有一个带有3个单元的CollectionView,它扩展到整个设备的屏幕,基本上代表了我的3个主要视图。
我启用了分页功能,因此它基本上与iOS主屏幕完全一样。
我的问题是我希望此CollectionView的“默认”位置等于view.frame.width以便第二个Cell是“默认”视图,我可以左右滑动以进入我的辅助视图。
我已经试过了

collectionView.scrollToItem()

collectionView.scrollRectToVisible()

以及

collectionView.setContentOffset()

但它们似乎只在视图加载后才起作用(我通过导航栏中的按钮尝试了它们)。 先感谢您!


编辑:
现在这个工作,但我在另一个中间单元格中还有另一个集合视图,它包含一个小的2页UICollectionView列表,它实际上来自UICollectionViewCell的子类,名为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)
            }
        }
    }
}

这是在执行viewDidLayoutSubviews我的“根”的CollectionViewController



编辑2:现在我尝试在MainCell类中使用以下代码(它是一个UICollectionViewCell子类):

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调用代码

好的,我明白了!
这个答案给了我最后的暗示:
https://stackoverflow.com/a/16071589/3338129
基本上,现在我只是在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,并在数据存在时立即将其切换,单元格在那里并且页面已滚动。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM