Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't select item in UICollectionView programmatically

I'm trying to set a default item when the view is loaded this way:

override func viewDidLoad() {
   super.viewDidLoad()

   self.collectionView.delegate = self
   self.collectionView.dataSource = self
   self.collectionView.allowsSelection = true
   self.collectionView.allowsMultipleSelection = true

}

I'm trying to select an item in the viewDidAppear method:

override func viewDidAppear(_ animated: Bool) {
    DispatchQueue.main.async(execute: {
        self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: UICollectionViewScrollPosition.bottom)
    })
}

But the didSelectItemAt method is not fired like I need.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
   //some config
}

Am I forgetting something?

like image 808
David Luque Avatar asked Jul 31 '17 10:07

David Luque


3 Answers

didSelectItemAt is not called if you call selectItem programmatically. You should call the method manually after it.

self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .bottom)
self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
like image 58
Tamás Sengel Avatar answered Nov 14 '22 14:11

Tamás Sengel


From documentation of selectItem(at:animated:scrollPosition:)

This method does not cause any selection-related delegate methods to be called.

That means you will have to call the delegate method manually.

like image 18
mag_zbc Avatar answered Nov 14 '22 13:11

mag_zbc


let indexPath = IndexPath(item: 0, section: 0)
DispatchQueue.main.async {
   self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .left)
}

This is the solution which is working for me. Hope this will help you.

like image 13
nitin.agam Avatar answered Nov 14 '22 14:11

nitin.agam