gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:27 24 4
gpt4 key购买 nike

现在我的 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
}

最佳答案

假设你有一个数组

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

关于ios - 如何在一个部分中组合相同的日期对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56109447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com