Как объединить одинаковые объекты даты в одном разделе? - PullRequest
1 голос
/ 13 мая 2019

Теперь мой 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 Ответ

4 голосов
/ 13 мая 2019

Если у вас есть массив

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

dic будет [Date:[Transaction]] рассматривать date ключ как раздел и значение [Transaction] как ряд разделов


numberOfsections

dic.keys.count

и

количество строк

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)})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...