Swift: How to perform didSelectItemAt for "modern" CollectionView

Viewed 131

I am testing out the "modern" UICollectionView for iOS14 and would like to perform didSelectItemAt when users tap on a cell. With the new implementation of CellRegistration and UICollectionViewDiffableDataSource, is there a new way to implement didSelectItemAt?

My current implementation is the traditional way:

lazy var collectionView: UICollectionView = {
    let config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
    let layout = UICollectionViewCompositionalLayout.list(using: config)
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.translatesAutoresizingMaskIntoConstraints = false
    cv.backgroundColor = .systemBackground
    cv.delegate = self //Set delegate here
    return cv
}()

extension TestController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath)
    }
}

While the above method works, the setting of delegate and didSelectItemAt appears to be extra boilerplate code. Is there a revised implementation to this? Nothing is mentioned in Apple's docs. Is didSelectItemAt still the default way?

1 Answers

Yes didselectitemAt remains same as before. You need to confirm to delegate and implement function collectionView(_:didSelectItemAt:) like before

Related