Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIcollectionView scrollToitemAtIndexPath does not work for non visible cells

I am new to iOS and Swift.

Have managed to create a UICollectionView with custom LayoutAttributes and reusable custom cell which calculates the height of it for an image. That's all great. Works fine and I can scroll manually. all good.

The problem is that I want to programatically scroll to the Nth indexPath but scrollToItemAtIndexPath seems to work only for the visible ones.

So I have to 2 columns of images which on iphone 5S shows 9 images. The total number of images is 31.

So using ScrollToItemAtIndexPath of the collectionView works up to the 9th item.

However, when I try to scroll programatically further, say 12th, it doesn't work. The weird bit is that if scroll manually, and then call the code, it works. So I debug a bit and have seen that only the first 9 cells are calculated with a height. Would that be the problem? If so, how could I make it work?

Have tried suggestions of using didLayoutSubviews and others but it didnt work.

At the moment, I am using the didSelectItemAtIndexPath collectionView func to scroll programmatically.

EDIT:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let item = self.collectionView(self.collectionView!, numberOfItemsInSection: 0) - 1
            let lastItemIndex = NSIndexPath(forItem: item, inSection: 0)
            self.collectionView?.scrollToItemAtIndexPath(lastItemIndex, atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: true)
}

Even if I hardcode the number of the index path (e.g. 12) it will still not work. If more information is required please let me know.

Am I missing something here?

many thanks.

like image 930
mox8iro Avatar asked Jun 17 '16 14:06

mox8iro


1 Answers

You should call the method scrollToItemAtIndexPath in the viewDidAppear, that way, the cellForItemAtIndexPath is already called.

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    collectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: index, inSection: 0), atScrollPosition: .CenteredVertically, animated: false)

}
like image 90
Lilo Avatar answered Sep 22 '22 09:09

Lilo