ios - scrollToItemAtIndexPath 破坏 UICollectionViewCell 布局

标签 ios objective-c iphone cocoa-touch uicollectionview

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

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

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

enter image description here

我做错了什么?

更多信息:

  • 我在 iOS 7 和 iOS 8 中都看到了这个错误。
  • 我在 Xcode 6.1 中使用大小类。

viewDidLayoutSubviews 的代码:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

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

最佳答案

每当我遇到这个问题并且我有一个固定大小的单元格时,我都会通过手动设置 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/

相关文章:

ios - Swift 3 - FTP 上传

ios - 使用 Web 服务 checkin 应用程序购买

ios - 如何在 iOS 中使用 UIImagePickerController 从 photoGallery 获取视频?

ios - 如何以一对多关系更新核心数据模型

ios - 在 swift 2.0 中允许用户播放背景音乐

ios - PFQueryTableViewController 快速按日期划分

ios - Watchkit动态通知按钮自定义

iphone - 加载 3 个 View Controller (使用 CALayer 绘制)的 ScrollView 性能不佳

iphone - iPhone 上的有损压缩格式为原始 PCM

ios - 如何调试在不是由 Xcode 启动的移动设备中执行的 iOS 应用程序?