Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uicollectionview select an item immediately after reloaddata?

After calling -[UICollectionView reloadData] it takes some time for cells to be displayed, so selecting an item immediately after calling reloadData does not work. Is there a way to select an item immediately after reloadData?

like image 214
last-Programmer Avatar asked Jan 08 '13 10:01

last-Programmer


3 Answers

Along the lines of this answer I found that calling layoutIfNeeded after reloadData seemed to effectively 'flush' the reload before I do other things to the collectionView:

[self.collectionView reloadData];
[self.collectionView layoutIfNeeded];
...

On the page I found this solution, some commenters indicated it didn't work for them on iOS 9, but it's been fine for me so your mileage may vary.

like image 94
user2067021 Avatar answered Nov 14 '22 16:11

user2067021


The Swift way:

let selected = collectionView.indexPathsForSelectedItems()
collectionView.performBatchUpdates({ [weak self] in
    self?.collectionView.reloadSections(NSIndexSet(index: 0))
    }) { completed -> Void in
        selected?.forEach { [weak self] indexPath in
            self?.collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: [])
        }
}
like image 7
Arsonik Avatar answered Nov 14 '22 16:11

Arsonik


I'm handling selection of cells in collectionView: cellForItemAtIndexPath:. The problem I found was that if the cell didn't exist, simply calling selectItemAtIndexPath: animated: scrollPosition: wouldn't actually select the item.

Instead you have to do:

cell.selected = YES;
[m_collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];

like image 4
Mark Ingram Avatar answered Nov 14 '22 15:11

Mark Ingram