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

标签 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
}

最佳答案

假设你有一个数组

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/

相关文章:

php - 用php中的另一个数组值替换一个数组键

c# - 删除 int 数组列表中的重复项

ios - UITableViewCell 每 5 个单元格重复一次(在标记为重复之前,请阅读整个任务)

ios - 将 SSL https 与 socket.io 和 swift 一起用于 iOS 应用程序

ios - 从左侧滑动 UIBarButtonItem

iphone - 如何 POST 请求以获得 JSON 响应

c - 如何将新元素添加到 C 中另一个结构数组内部的数组中?

IOS Swift,如何检测文件上传点击UIWebView内部打开照片上传对话框

ios - 如何在 PhoneGap/Cordova 2.0 中使用预填充的 SQLite 数据库?

swift - 根据百分比填充描边颜色,即 80%、70% 或任何其他百分比