Can't select item in UICollectionView programmatically

Viewed 12904

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?

6 Answers
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.

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

self.activityCollectionView?.scrollToItem(at: IndexPath(row: 1, section: 0), at: UICollectionViewScrollPosition.right, animated: true)

}

//viewDidAppear is the key

For my case, I need to combine Tamàs and iDev750's answer:

DispatchQueue.main.async {
    self.collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .bottom)
    self.collectionView(self.collectionView, didSelectItemAt: IndexPath(item: 0, section: 0))
}

None of above answer worked with me because cell in IndexPath(item: 0, section: 0) in my collectionView isn't visible so my app crashed. Than i fixed it with scrolling to [0,0] and waiting until collectionView finishes its animation then selected item with calling delegate method didSelectItemAt manually. Now it works perfectly.

Example Code:

/** scroll to cell that you want to select it */
layoutsCollectionView.selectItem(at: .init(item: 0, section: 0),
                                         animated: true,
                                         scrollPosition: .centeredHorizontally)

/** implement UIScrollViewDelegate in your view controller and call */
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {

    /** 
     * here scroll animation finished thats mean your cell is visible
     * now you can select your cell with delegate method
     */
    layoutsCollectionView.delegate?.collectionView?(self.layoutsCollectionView, didSelectItemAt: [0,0])
}
Related