如何将集合视图设置为第n个元素

hap*_*497 1 ios uicollectionview swift

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

我想在首次启动时将uicollecitonView设置为指定的元素.有人建议我使用'将集合视图的contentOffset设置为(集合视图宽度)*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.
Run Code Online (Sandbox Code Playgroud)

在我的集合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 }
Run Code Online (Sandbox Code Playgroud)

我总是看到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)
        }
}
Run Code Online (Sandbox Code Playgroud)

rob*_*off 5

通常,集合视图使用带有节和项的索引路径.尝试newIndex以下方式创建viewDidAppear:

let newIndex = NSIndexPath(forItem:self.index inSection:0)
Run Code Online (Sandbox Code Playgroud)

  • 尝试从`viewDidLayoutSubviews`而不是`viewDidAppear`调用`scrollToItemAtIndexPath`. (3认同)