簡體   English   中英

如何使用 RxDataSource 制作動態部分?

[英]How to make Dynamic sections with RxDataSource?

我要實現的目標的概述我正在嘗試制作一個通知表格視圖,並且每個通知都按其創建日期分組,因此表格視圖部分將是創建日期的數量,每個部分都包含在此日期創建的通知部分標題。 我進行了很多搜索,但沒有得到絕對答案如何使用 RxDataSource 使數組動態加載通過 API 接收的日期?

class T : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return array.count
    }
}

我發現的只是像這樣設置 static 部分

       ViewModel.AllNotificationsObservable
                .map({ [NotificationSectionViewModel(header: "Yet", items: $0.filter{$0.createAt.toDate()!.toString(format: "yyyy-MM-dd") == Date().toString(format: "yyyy-MM-dd") }),
                        NotificationSectionViewModel(header: "Yesterday", items: $0)
                ]
                })
                .bind(to: NotificationTableView.rx.items(dataSource: ViewModel.dataSource))
                .disposed(by: notificationDisposeBag)

這是我的結構

struct NotificationSectionViewModel {
    var header: String
    var items: [AllNotificationModel] 
}
extension NotificationSectionViewModel: SectionModelType {
    typealias NotificationItem = AllNotificationModel
    
    init(original: NotificationSectionViewModel, items: [AllNotificationModel]) {
        self = original
        self.items = items
    }
}

這是數據 model

class AllNotificationModel : Codable {
    
    let id, userID : Int
    let title, body, createAt: String
    
    enum CodingKeys: String, CodingKey {
        case id, title, body
        case userID = "user_id"
        case createAt = "create at"
    }
}

我想要達到的目標

在此處輸入圖像描述

需要 header 是這樣的

“Today”: [
        {
            "id": 2421,
            "user_id": 39,
            "title": "todayNotification",
            "body": "test",
            "create at": "2021-02-26 17:33:44"
        },
        {
            "id": 2349,
            "user_id": 39,
            "title": "check",
            "body": "test",
            "create at": "2021-02-26 09:36:05"
        },
        {
            "id": 2206,
            "user_id": 39,
            "title": "New Deal",
            "body": "new Deal 2",
            "create at": "2021-02-26 13:43:16"
        } ]
“Yesterday”: [
        {
            "id": 2134,
            "user_id": 39,
            "title": "Closed Deal",
            "body": “deal deal”,
            "create at": "2021-02-25 13:21:30"
        } ]

“2021-02-24”: [
        {
            "id": 2134,
            "user_id": 39,
            "title": "Closed Deal",
            "body": “deal”,
            "create at": "2021-02-24 13:21:30"
        },
        {
            "id": 2063,
            "user_id": 39,
            "title": "New Deal",
            "body": "new Deal",
            "create at": "2021-02-24 13:21:16"
        }]

在 RxDataSources 的示例中,我們有:

Observable.just(sections)
  .bind(to: tableView.rx.items(dataSource: dataSource))
  .disposed(by: disposeBag)

您需要做的就是將 Observable.just(sections) 替換為綁定到您的數據的 Observable。 假設notifications是一個Observable<[Notifications]> 然后你做這樣的事情:

notifications.map { sections(from: $0) }
  .bind(to: tableView.rx.items(dataSource: dataSource))
  .disposed(by: disposeBag)

sections(from: $0)[Notification]數組到sections數組的轉換,在某處定義它。 您的部分結構必須符合協議SectionModelType

struct SectionOfNotification {
  var header: String    
  var items: [Item]
}

extension SectionOfNotification : SectionModelType {
  typealias Item = Notification

   init(original: SectionOfNotification, items: [Item]) {
    self = original
    self.items = items
  }
}

我的例子:

public lazy var appSections: Driver<[AppSection]> = {
    Driver.combineLatest(chatAppCollectionData, functionAppCollectionData) { ($0, $1) }
        .map { (chatAppCollectionData, functionAppCollectionData) -> [AppSection] in
            let appSection1 = AppSection(header: NSLocalizedString("DASHBOARD_RECENT_CHATS", comment: ""),
                                         items: chatAppCollectionData)

            let appSection2 = AppSection(header: NSLocalizedString("DASHBOARD_OTHERS", comment: ""),
                                         items: functionAppCollectionData)

            return [
                appSection1,
                appSection2
            ]
        }
}()

這是部分:

import RxDataSources

struct AppSection {
    var header: String
    var items: [Item]
}

extension AppSection: SectionModelType {
    typealias Item = EONApp

    init(original: AppSection, items: [Item]) {
        self = original
        self.items = items
    }
}

我想出了答案

override func bind(ViewModel: NotificationViewModel) {

        
        ViewModel.dataSource.configureCell = { [unowned self] (dataSource, tableview, indexPath, item)  in
            let cell = tableview.dequeueReusableCell(withIdentifier: self.CellIdentifier, for: indexPath) as! NotificationTableViewCell
            cell.setDataToUI(notificationData: item)
            return cell
        }

        ViewModel.dataSource.titleForHeaderInSection = { (dataSource, index) in
            let section = dataSource[index]
            return section.header
        }
    
        var finalSections = [NotificationSectionViewModel]()
        var sortedFinal = [NotificationSectionViewModel]()
        var result = [String : [AllNotificationModel]]()
            ViewModel.AllNotificationsObservable
                .map({ section in
      for (i, dict) in section.enumerated() {
                        result[(section[i].createAt.toDate()?.toString(format: "yyyy-MM-dd"))!, default: []].append(dict)
                    }
                    
                    for (key, value) in result {
                        finalSections.append(NotificationSectionViewModel(header: key, items: value))
                    }
                    
                    sortedFinal = finalSections.sorted(by: >)
                    
                    for final in 0...sortedFinal.count - 1 {
                        if self.getTodayDate() == sortedFinal[final].header {
                            sortedFinal[final].header = "Today"
                        }
                        else if self.getYesterDay() == sortedFinal[final].header {
                            sortedFinal[final].header = "Yesterday"
                        }
                        else {
                                sortedFinal[final].header = convertDateFormater(sortedFinal[final].header)
                            
                        }
                    }
                    
                    return sortedFinal
                })
                .bind(to: NotificationTableView.rx.items(dataSource: ViewModel.dataSource))
                .disposed(by: notificationDisposeBag)
}

這是我的手機 class

class NotificationTableViewCell: UITableViewCell {

    @IBOutlet weak var notificationImageIcon: UIImageView!
    @IBOutlet weak var notificationBodyMessage: UILabel!
    @IBOutlet weak var notificationTime: UILabel!
    @IBOutlet weak var seenNotificationView: UIView!
    

    override func awakeFromNib() {
          super.awakeFromNib()
          // Initialization code
          selectionStyle = .none
      }

    func setDataToUI(notificationData: AllNotificationModel) {
        DispatchQueue.main.async {
            self.seenNotificationView.isHidden = true
            self.notificationBodyMessage.text = notificationData.body
            self.notificationTime.text = self.convertDateFormater(notificationData.createAt)
        }
    }
    
    func convertDateFormater(_ date: String) -> String
        {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let date = dateFormatter.date(from: date)
            dateFormatter.dateFormat = "h:mm a"
            return  dateFormatter.string(from: date!)

        }

}

我用這兩個 function 來獲取今天和昨天的日期

extension UIViewController {
    func getTodayDate() -> String {
        let currentDate = Date()
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd"
        let dateString = df.string(from: currentDate)
        return dateString
    }

    func getYesterDay() -> String {
        let currentDate = Date.yesterday
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd"
        let dateString = df.string(from: currentDate)
        return dateString
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM