Home / IOS Development / ios – How to update section footer via DiffableDataSource without causing flicker effect?

ios – How to update section footer via DiffableDataSource without causing flicker effect?



A section can contain 1

header, many content elements and 1 footer.

To DiffableDataSource, most examples online, use enum to represent section. For example

func applySnapshot(_ animatingDifferences: Bool) {
    var snapshot = Snapshot()
    
    snapshot.appendSections([.MainAsEnum])

    snapshot.appendItems(filteredTabInfos, toSection: .MainAsEnum)

    dataSource?.apply(snapshot, animatingDifferences: animatingDifferences)
}

However, when the section has a footer with dynamic content, we may need to use struct to represent the section. For example

import Foundation

struct TabInfoSection {

    // Do not include content items [TabInfo] as member of Section. If not, any mutable 
    // operation performed on content items, will misguide Diff framework to throw 
    // away entire current Section, and replace it with new Section. This causes 
    // flickering effect.

    var footer: String
}

extension TabInfoSection: Hashable {
}

But how do we just update the footer?

The current approach given by

DiffableDataSource: Snapshot Not loading header and footer is not completely accurate

If I try to update footer

class TabInfoSettingsController: UIViewController {
    …

    func applySnapshot(_ animatingDifferences: Bool) {
        var snapshot = Snapshot()

        let section = tabInfoSection;
        
        snapshot.appendSections([section])

        snapshot.appendItems(filteredTabInfos, toSection: section)

        dataSource?.apply(snapshot, animatingDifferences: animatingDifferences)
    }

var footerValue = 100

extension TabInfoSettingsController: TabInfoSettingsItemCellDelegate {
    func crossButtonClick(_ sender: UIButton) {
        let hitPoint = (sender as AnyObject).convert(CGPoint.zero, to: collectionView)
        if let indexPath = collectionView.indexPathForItem(at: hitPoint) {
            // use indexPath to get needed data

            footerValue = footerValue + 1
            tabInfoSection.footer = String(footerValue)
            
            //
            // Perform UI updating.
            //
            applySnapshot(true)
        }
    }
}

I get the following flickering outcome.

enter image description here

The reason for flicker is that the diff framework discards the entire old section, and replaces it with a new section, as it detects that there is a change in TabInfoSection object.

Is there a good way to update footer in section via DiffableDataSource without causing flickering effect?

p / s The entire project source code can be found in https://github.com/yccheok/ios-tutorial/tree/broken-demo-for-footer-updating under the TabDemo folder.


Source link