如何在一个部分中合并相同的日期对象?

时间:2019-05-13 09:27:58

标签: ios arrays swift xcode date

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

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

enter image description here

我想在这张图片上做个赞。 enter image description here

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

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
}

}

1 个答案:

答案 0 :(得分:4)

假设您有一个数组

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

dic[Date:[Transaction]]视为date键作为节,并将值[Transaction]视为节行


  

numberOfsections

dic.keys.count

  

numberofRows

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)})