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

518 views Asked by At

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.

0

There are 0 answers