ios - 如何将 Collection View 设置为第 n 个元素

标签 ios swift uicollectionview

我有 1 个 ViewController,它将启动另一个具有 CollectionView 的 ViewController。

我想在 uicollecitonView 首次启动时将其设置为指定的元素。 在之前的帖子中,有人建议我使用“将 Collection View 的 contentOffset 设置为( Collection View 宽度)* selectedRow”。但我无法让它工作。

在我的 prepareForSegue 函数中,我添加了:

  x = Float(indexPath.row) * 375.0 // 375 is the width of 1 cell
  var point = CGPointMake(CGFloat(x), 0)
  println ("***x=")
  println (x)
  detailController.collectionView?.setContentOffset(point , animated: false)
where detailController is UICollectionViewController.

在我的 Collection View 的 UICollectionViewDataSource 中,我总是看到它获取第 0 个元素,而不是第 n 个元素

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as DetailViewCell

        // Configure the cell
        println("DetailViewController in cellForItemAtIndexPath()")
        println(indexPath.row)
     cell.myitem = allItems[indexPath.row]
return cell }

而且我总是看到 cellForItemAtIndexPath 试图获取 allItems 的第 0 个元素(即我所有对象的整个集合。

有解决办法吗?

更新:

谢谢。我试过我得到这个异常:* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“尝试滚动到无效的索引路径:{length = 1,path = 4}”

我确定我的列表中有 26 项。为什么当我想滚动到第 4 个元素时只有 1:

class MyViewCollectionViewController: UICollectionViewController {

    override func viewDidAppear(animated: Bool) {
            println("MyViewCollectionViewController viewDidAppear")

            println("items.count")
            println(items?.count)  // print out 26

            println(index) // print out 4

            var newIndex = NSIndexPath(index: self.index)
            self.collectionView?.scrollToItemAtIndexPath(newIndex, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
}

最佳答案

通常, Collection View 使用带有部分和项目的索引路径。尝试在 viewDidAppear 中以这种方式创建 newIndex:

let newIndex = NSIndexPath(forItem:self.index inSection:0)

关于ios - 如何将 Collection View 设置为第 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25936493/

相关文章:

ios - XCUITest - 如何检查 webview 是否已更新其内容?

ios - UIImage 如何使用 capInsets 调整气泡图像的大小?

iOS 8 : When App in Background CBCentralManager Delegate Method didDiscoverPeripheral, didConnectPeripheral、didFailToConnectPeripheral 未调用

ios - 当应用程序不活动时,Swift 中的 Firebase 消息不显示

ios - 更改 UICollectionView 中特定单元格的图像

ios - viewForSupplementaryElementOfKind 没有被调用

ios - 如何在 UISplitViewController UISplitViewControllerDisplayModePrimaryOverlay 模式下更改分隔符的颜色

ios - 如何检测 UITableView 何时完成加载所有行?

ios - 在 Swift 中存储和使用庞大的字典

iphone - 在包含 UICollectionView 和 UIImageView 的主视图中垂直滚动