我有一个带有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
的{{1}}中执行的。
编辑2:
现在我尝试在CollectionViewController
类中使用以下代码(它是MainCell
子类):
UICollectionViewCell
编辑3:
长话短说,我基本上需要一个名为的委托方法,将一个单元格添加到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)
}
。
答案 0 :(得分:1)
您是否尝试过[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
尝试调用viewDidLayoutSubviews
答案 1 :(得分:0)
好的,我明白了!
这个答案给了我最后的暗示:
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,并在数据存在时将其切换为打开,单元格在那里并且页面已滚动。