I tried to write
[self collectionView:myCollectionView didSelectItemAtIndexPath:selectedIndexPath]
and UICollectionViewCell's selected=YES in viewDidLoad, and it did implemented the method didSelectItemAtIndexPath
, but the cell not selected.
I wrote the selected state in UICollectionViewCell subclass's (void)setSelected:(BOOL)selected
. After the view was load, the manual selection function works. But I could't let it auto selected some items after the view's first load.
And I tried to write codes in:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
and
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
, all not OK.
I found it first run viewDidLoad
and didSelectItemAtIndexPath
, then cellForItemAtIndexPath
, it seems like that I could't get the cell in the indexPath
(that I know) before cellForItemAtIndexPath
, because before that the cell is not exist. So how to select some items in the UICollectionView
after it first load?
Sorry for my poor english. Thanks in advance.
Not sure, if got your question correct, but here's a possible solution:
In e.g. viewWillAppear:
do
[self.collectionView reloadData];
NSIndexPath *selection = [NSIndexPath indexPathForItem:THE_ITEM_TO_SELECT
inSection:THE_SECTION];
[self.collectionView selectItemAtIndexPath:selection
animated:YES
scrollPosition:UICollectionViewScrollPositionNone];
Bear in mind, that calling 'selectItemAtIndexPath' programmatically does NOT call the related delegate methods; you'll have to call them in code if you need them.
In my case selectItemAtIndexPath
had no effect after reloadData
, so I had to call it in the completion block of performBatchUpdates
:
collectionView.dataSource = ...
collectionView.delegate = ...
let indexPath = ...
collectionView.performBatchUpdates(nil) { _ in
collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
Swift 3
Implement this override function where is your collectionview is created. Assuming that we have 1 section 1 row like Instagram stories.
override func viewDidAppear(_ animated: Bool) {
// Auto Select First Item
self.myCollectionView.performBatchUpdates(nil) { _ in
self.myCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: [.centeredHorizontally])
self.collectionView(self.myCollectionView, didSelectItemAt : IndexPath(item: 0, section: 0))
}
}
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