本文介绍了如何在一个部分中合并相同的日期对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我的tableView按日期排序,但是如果日期相同,我还需要将它们连接到一个部分中。请告诉我该怎么做?

Now my tableView is sorted by date, but I also need to, if the dates are the same, connect them into one section. Please tell me how to do this?

class Transaction {
   var amount = "0"
   var date = Date()
   var note = ""
}

我想在此图片上添加图片。

I want to make like on this image.

所有升级结果都是以前的。

After all upgradings result is former.

class OperationsViewController: UITableViewController {

var transactions: Results<Transaction>!
var dic = [String : [Transaction]]()

override func viewDidLoad() {
    super.viewDidLoad()
    transactions = realm.objects(Transaction.self)
    // transactions = realm.objects(Transaction.self).sorted(byKeyPath: "date", ascending: false)

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dic = Dictionary(grouping: transactions, by: {dateFormatter.string(from: $0.date) })
}

override func viewWillAppear(_ animated: Bool) {
    super .viewWillAppear(animated)
    tableView.reloadData()
}

//  MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return dic.keys.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dic[Array(dic.keys)[section]]?.count ?? 0
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

 return ???
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "operationCell", for: indexPath) as! OperationsViewCell
    let keys = Array(dic.keys)
    let item = dic[keys[indexPath.section]]!
    let transaction = item[indexPath.row]

    cell.categoryLabel.text = transaction.category.rawValue
    cell.amountLabel.text = creatMathSymbols(indexPath) + transaction.amount + " " + "₴"
    cell.noteLabel.text = transaction.note

    return cell
}

}

推荐答案

假设您有一个数组

let arr = [Transaction]()  
let dic = Dictionary(grouping: arr, by: { $0.date})

dic 将为 [日期:[Transaction]] date 键作为部分,并将值 [Transaction] 作为部分行

dic will be [Date:[Transaction]] consider date key as section and value [Transaction] as sections rows



dic.keys.count



let keys = Array(dic.keys)

let item = dic[keys[section]]!

return item.count






编辑:

let form = DateFormatter()
form.dateFormat = "yyyy-MM-dd"

let arr = [Transaction]()
let dic = Dictionary(grouping: arr, by: {form.string(from: $0.date)})

这篇关于如何在一个部分中合并相同的日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 13:38