How to programmatically select cell in collectionView in swift 3?

xcalysta picture xcalysta · Aug 4, 2017 · Viewed 7.7k times · Source

I'm new to swift and been having trouble programmatically selecting collectionview cells in collectionView. I've found only instructions for tableview but ran into an error when tried to implement it.

 let indexPath = IndexPath(row: 0, section: 0)
    appsCollectionView.selectItem(at: indexPath, animated: false, scrollPosition: .bottom)
    appsCollectionView.delegate?.collectionView!(appsCollectionView, didSelectItemAt: indexPath)

According to other answers, you need both lines 2 and 3. Not sure what line 3 is doing. When I try to run this code, I got the error

collectionView:didSelectItemAtIndexPath:]: unrecognized selector sent to instance

Thanks!

Answer

Ferschae Naej picture Ferschae Naej · Aug 4, 2017

This error basically just tells you that you didn't implement the UICollectionViewDelegate protocol collectionView(_,didSelectItemAt:_) method, but I don't think you are supposed to call the method directly (line 3).

I'm pretty sure calling selectItem(at:,animated:,scrollPosition:) (line 2) is enough. The collection view should scroll to the selected cell and the cell appearance should change to the selected state. But maybe your cell appearance doesn't change when selected, which makes you believe it's not selected?

If it's not already the case, in your UICollectionViewCell subclass, override the following properties and, for example, change the color of some label:

override var isHighlighted: Bool {
    didSet {
        titleLabel.textColor = isHighlighted || isSelected ? .black : .darkGray
    }
}

override var isSelected: Bool {
    didSet {
        titleLabel.textColor = isHighlighted || isSelected ? .black : .darkGray
    }
}

Then try to call only selectItem(at:,animated:,scrollPosition:) and maybe you'll notice a difference.

Note: As written in the selectItem(at:,animated:,scrollPosition:) method documentation:

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

It will just change the cell state to selected, not call any action that would have been called if you would have tapped on the cell.