Created
May 3, 2020 22:51
-
-
Save aidaan/9049dce898e40f623aecacfa136d1077 to your computer and use it in GitHub Desktop.
A UITableViewDiffableDataSource subclass with support for section titles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
open class SectionTitledDiffableDataSource<SectionIdentifierType, ItemIdentifierType>: UITableViewDiffableDataSource<SectionIdentifierType, ItemIdentifierType> | |
where SectionIdentifierType : Hashable, ItemIdentifierType : Hashable { | |
public typealias SectionTitleProvider = (UITableView, SectionIdentifierType) -> String? | |
open var sectionTitleProvider: SectionTitleProvider? | |
open var useSectionIndex: Bool = false | |
open override func sectionIndexTitles(for tableView: UITableView) -> [String]? { | |
guard useSectionIndex, let sectionTitleProvider = sectionTitleProvider else { return nil } | |
return snapshot().sectionIdentifiers.compactMap { sectionTitleProvider(tableView, $0) } | |
} | |
open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { | |
sectionTitleProvider?(tableView, snapshot().sectionIdentifiers[section]) | |
} | |
open override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { | |
guard useSectionIndex else { return 0 } | |
return snapshot().sectionIdentifiers.firstIndex(where: { sectionTitleProvider?(tableView, $0) == title }) ?? 0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment