ios - 如何设置加载 uicollectionview 时选择的项目?

标签 ios swift scroll collectionview nsindexpath

我想在加载 View 时将滚动设置为所选项目。我有如下所示的工具。但它崩溃了。

self.collectinView.scrollToItemAtIndexPath(self.selected_indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)

这是我收到的错误:

2017-03-23 19:52:45.918645 com.CodeZync.Taxi.iOSClient[7936:1702109] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: {length = 2, path = 0 - 1}' *** First throw call stack: (0x1d09cdf7 0x1c2ff077 ) libc++abi.dylib: terminating with uncaught exception of type NSException

最佳答案

所以indexPath还不可见。确保您已将适当的数据添加到collectionView中,然后在viewDidLoad()

内部执行collectionView.reloadData()

然后在 viewDidAppear() 中放置您的行,如果您想像您所说的那样选择单元格,请添加以下内容:

self.collectionView.selectItem(at: IndexPath(item: 0, section: 1), animated: true, scrollPosition: UICollectionViewScrollPosition.CenteredHorizontally))

调用 super.viewDidAppear(animated) 后,在 viewDidAppear(_animated: Bool) 中进行选择和滚动将使动画可见。

错误的原因是当您调用选择时 Collection View 为空,因此它崩溃了。

关于ios - 如何设置加载 uicollectionview 时选择的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42978735/

相关文章:

ios - 导航栏隐藏时的样式状态栏

ios - SQLite 查询占用太多 CPU

ios - 查找来自每个发件人的最新消息?

swift - 如何限制泛型函数以防止使用数组和字典?

uitableview - swift 为 UITableView 加载更多内容

ios - 子类 MKTileOverlay 未显示在 map 上

iphone - 使用NSURL从另一个应用程序启动应用程序

ios - 如何在 UITabBarController 中显示 ViewController?

jquery - 水平滚动到 div 不起作用

javascript:scrollTop 和 offsetTop 之间的区别