Search code examples
iosswiftuicollectionviewlong-pressdiffabledatasource

UICollectionViewController + diffableDataSource - cell gets unhighlighted while your finger is still on it


If I am using UICollectionViewController with diffableDataSource and tapping on cell - it highlights, but then gets unhighlighted while I'm still holding finger on it. If to use UIViewController + collectionView with diffableDataSource - then everything working as intended, and cell keeps highlighted until I release finger from it. The same if to use UICollectionViewController with standard dataSource - everything working good. Has anyone noticed this problem as well? Any advice or thoughts would be appreciated, maybe I'm just missing something, but for now it feels more like a bug from Apple side

You can see the example here: https://github.com/ashishbl86/MockAppStore/blob/0ea8e74a4823c8c80bd7e8d5c6a9514958fbe459/MockAppStore/CollectionViewController.swift

Just add to CollectionViewController.swift file these methods:

override func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
        print("cell highlighted")
    }
    
    override func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
        print("cell unhighlighted")
    } 

and you'll see that "cell unhighlighted" is printed while your finger is still on a cell


Solution

  • okay as it turned out we need to set

    installsStandardGestureForInteractiveMovement = false
    

    this variable installs a standard gesture recogniser for UICollectionViewController to drive the reordering process. It is set to true by default, but in order to make things work the collectionView dataSource must declare its support for reordering items by implementing the appropriate methods. In old good dataSource methods moveItemAt are marked as optional, while in diffableDataSource it is not declared as optional any more, which is the reason for this variable to cause the behaviour described in the issue above. More info about this variable available in docs: https://developer.apple.com/documentation/uikit/uicollectionviewcontroller/1623979-installsstandardgestureforintera