Reputation: 163225
I have 1 ViewController and it will launch another ViewController which has a CollectionView.
I want to set the uicollecitonView to a specified element when it first start. In previous thread someone suggests me to use ' set the contentOffset of the collection view to (collection view width) * selectedRow'. But I can't get that to work.
In my prepareForSegue function, I have added:
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.
and in the UICollectionViewDataSource of my collection View, I always see it get the 0th element, not the nth element
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 }
And I always see cellForItemAtIndexPath trying to get 0th element of the allItems (that is the whole collections of all my objects.
Any idea to solve this?
Update:
Thanks. I tried I get this exception: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: {length = 1, path = 4}'
I am sure I have 26 items in my list. Why there is only 1 when I want to scroll it to 4th element:
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)
}
}
Upvotes: 1
Views: 3172
Reputation: 385910
Usually a collection view uses index paths with a section and an item. Try creating newIndex
this way in viewDidAppear
:
let newIndex = NSIndexPath(forItem:self.index inSection:0)
Upvotes: 5