0

How to show the same object in different sections by using Diffable data sources?

Here is the Model :-

// MARK: - RecentUsers
struct RecentUsersModel: Codable, Hashable {
   let errorCode: Int?
   let message: String?
   let result: RecentUsersResult?
}

// MARK: - Result
struct RecentUsersResult: Codable, Hashable {
   let recentUsers: [AllUsersContactList]?
   let friendUsers: [AllUsersContactList]?
}

// MARK: - ContactList
struct AllUsersContactList: Codable, Hashable {
   let userID: Int?
   let name: String?
   let image: String?

enum CodingKeys: String, CodingKey {
    case userID = "userId"
    case name, image
 }
}

Code for Diffable Data Sources

var dataSourceRecentUsers : UITableViewDiffableDataSource<RecentUsersSection, AllUsersContactList>!

//MARK: Recent User Data Source
func createRecentUsersDataSource(){
    dataSourceRecentUsers = UITableViewDiffableDataSource(tableView: tableView, cellProvider: { tableView, indexPath, data in
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "ContactsTableViewCell") as? ContactsTableViewCell else { return UITableViewCell()}
        cell.labelName.text = data.name
        return cell
        
    })
}

func createRecentUserSnapShots(data : RecentUsersModel?){
    var snapShot = NSDiffableDataSourceSnapshot<RecentUsersSection, AllUsersContactList>()
    snapShot.appendSections([.recentUsers,.friends])
    snapShot.appendItems(data?.result?.recentUsers ?? [], toSection: .recentUsers)
    snapShot.appendItems(data?.result?.friendUsers ?? [], toSection: .friends)
    dataSourceRecentUsers.apply(snapShot,animatingDifferences: true)
}

Here is the code to create SnapShots, now what if i have same user in recentUsers model and friendsList model & i want to show both in different sections of a tableView.

3
  • IIRC, you just need to give the items different identifiers. That way a "item A" on the first row is a distinct entity as an "item A" on the third row, and that identity is stable across reorderings.
    – Alexander
    Commented Sep 5, 2022 at 16:05
  • @Alexander can't i put same identifier for both item not even in different sections? Commented Sep 5, 2022 at 16:07
  • I'm not sure I understand your question. If you put the same identifier for two items, the system won't be able to distinguish them, which will lead to all kinds of bugs.
    – Alexander
    Commented Sep 5, 2022 at 16:14

0

Browse other questions tagged or ask your own question.