OGeek|极客世界-中国程序员成长平台

标题: ios - scrollToItemAtIndexPath 破坏 UICollectionViewCell 布局 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:56
标题: ios - scrollToItemAtIndexPath 破坏 UICollectionViewCell 布局

我正在创建一个水平滚动的分页 UICollectionView,其单元格与 Collection View 一样大,因此一次只显示一个单元格。我还想在 Collection View 首次出现时首先显示最后一个项目,以便从左侧显示其他项目,而不是从右侧显示下一个项目的默认值。

为此,我按照 this answer 的建议在 View Controller 的 viewDidLayoutSubviews 中调用 scrollToItemAtIndexPath: .如果我在 viewWillAppear 或 viewDidLoad 中调用 scrollToItemAtIndexPath,则 Collection View 根本不会滚动到最后一项。

但是,此调用破坏了我的 Collection View 单元格的布局。例如,如果我不调用 scrollToItemAtIndexPath:,则 Collection View (下方的白色区域)看起来像左边的——布局正确但显示了第一个项目。如果我调用 scrollToItemAtIndexPath:, Collection View 最初会显示最后一项,但布局会像右侧一样困惑(甚至不再显示日期)。

enter image description here

我做错了什么?

更多信息:

viewDidLayoutSubviews 的代码:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:self.unit.readings.count - 1 inSection:0];
    [self.readingCollectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}



Best Answer-推荐答案


每当我遇到这个问题并且我有一个恒定大小的单元格时,我都会通过手动设置 contentOffset 并忽略 collectionView 方法来解决它。

self.collectionView.contentOffset = (CGPoint){
  .x = self.collectionView.contentSize.width - cell.width,
  .y = 0,
};

关于ios - scrollToItemAtIndexPath 破坏 UICollectionViewCell 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26947366/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4