Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically select cell in collectionView in swift 3?

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!

like image 596
xcalysta Avatar asked Jun 05 '26 10:06

xcalysta


2 Answers

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.

like image 194
Ferschae Naej Avatar answered Jun 07 '26 23:06

Ferschae Naej


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

You do not need to call the collectionView delegate method explicity. Instead, if you have just set the delegate then just implement the method.

optional func collectionView(_ collectionView: UICollectionView, 
             didSelectItemAt indexPath: IndexPath)
like image 24
Hussain Shabbir Avatar answered Jun 08 '26 00:06

Hussain Shabbir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!