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
?
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.
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: [])
}
}
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With