Answer the question
In order to leave comments, you need to log in
Trouble adding sections to TableView?
Hello, perhaps the question is trivial, but still I have a gag.
I add the realm table to the TableView The
realm database contains the Spending table with the headings: category(string), sum(int), day(int).
It is necessary that in the TableView the category and the amount are displayed in sections by day.
In my implementation, sections with the same cell contents are displayed.
Please tell me what is wrong.
my code:
extension ViewController:UITableViewDelegate,UITableViewDataSource {
//количество строк в секции
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {///сюда
// возвращаем количество записей в массиве
// считаем сколько дат есть в таблице
let section = spendingArray[section].day
return section
}
//количество секций
func numberOfSections(in tableView: UITableView) -> Int {
var num = Array<Int>()
for i in spendingArray{// создаем массив из дней
num.append(i.day)
}
let unique = Array(Set(num)) //создаем массив из уникальных элементов
return unique.count
}
// заголовок секции
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "\(section)"
}
//ширина ячеек в таблице
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
// параметры ячейки
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell
// переменнная влючающая все элементы массива spendingArray, которые будут совпадать по индексам
var num = Array<Int>()
for i in spendingArray{// создаем массив из дней
num.append(i.day)
}
let section = spendingArray[indexPath.section]
let spending = section[indexPath.row] // в секции ищем дату
cell.recordCategory.text = spending.category
cell.recordSum.text = "\(spending.sum)" //интерпаляция строк
return cell
}
Answer the question
In order to leave comments, you need to log in
I advise you to convert your spendingArray into a separate object that will be with the structure that you are comfortable working with.
Those. - either an array of objects of the DaySection type, in which categories and sums will be collected,
or a Dictionary in which the keys are the Day, and the value of the category and sums.
then it will be easier and clearer to work. And you will make the transformation once before updating the table, and not when each cell is updated.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question