Swift-按日期对在tableviewSections中从数据库收到的对象进行排序

我有一个应用程序,该应用程序从数据库接收交易并按日期顺序在表格视图中显示交易。现在,我想将每天的交易放在这样的单独部分中:

Today: 
transaction455
transaction454

Yesterday:
transaction453

Tuesday,12.11:
transaction452
transaction451
transaction450

事务对象在Unix中有一个“ createDate”,因此我必须先将其转换为日期。然后,我将var sectionHeaders = [String]()

中的所有日期排序

我的主要问题是numberOfRowsInSection,我已经看过并阅读了许多有关如何实现此功能的教程,但我完全不能。到目前为止,这是我的代码:

分组交易:

var sectionHeaders = [String]()

func groupTransactions() {
        print("Attemt to group transactions based on date")

        let sortedTransactionSections = transactions.sorted(by: {$0.createdDate > $1.createdDate})

        let groupedTransactions = Dictionary(grouping: sortedTransactionSections) { (element) -> String in
            return unixToString(t: Double(element.createdDate),f: "EEEE,dd MM")
        }

        groupedTransactions.keys.forEach { (key) in
            sectionHeaders.append(key)
        }

        let sorted = sectionHeaders.sorted(by: {$0 > $1})
        print(sorted)

    }

此分组中的一个大问题是分组取决于当天的首字母。 因此,所有“星期五”都应该是“星期五”,然后是“星期一”,然后是“星期六”,依此类推...我希望它们按照实际日期分组:“ 14.11.2019”,“ 13.11.2019”,“ 12.11.2019”等...

Tableview:

func numberOfSections(in tableView: UITableView) -> Int {
        if isSearching {
            return 1
        } else {
            return sectionHeaders.count
        }
    }

    func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
        return sectionHeaders[section]
    }

    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {

        if isSearching {
            return filteredTransactions.count
        } else {

            return transactions.count
        }

    }

    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as! TransactionCell

        cell.selectionStyle = .none

        var rec: Transactions
        transactions = transactions.sorted(by: {$0.createdDate > $1.createdDate})

        if isSearching {
            rec = filteredTransactions[indexPath.row]
        } else {
            rec = transactions[indexPath.row]
        }

        cell.dateLabel.text = unixToString(t: Double(rec.createdDate),f: "H:mm MMM dd")
        cell.amountLabel.text = rec.transactionTotal.convertPrice

        return cell
    }

sswwhh01 回答:Swift-按日期对在tableviewSections中从数据库收到的对象进行排序

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3104205.html

大家都在问