Mikhail Tseitlin
Mikhail Tseitlin

Reputation: 109

How to combine the same date objects in one section?

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 = ""
}

enter image description here

I want to make like on this image. enter image description here

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
}

}

Upvotes: 1

Views: 552

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Assuming you have an array

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

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


numberOfsections

dic.keys.count

and

numberofRows

let keys = Array(dic.keys)

let item = dic[keys[section]]!

return item.count

Edit:

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

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

Upvotes: 4

Related Questions