I'm trying to section my Tableview data based on a Key in my Firebase database.
I'm able to section everything properly based on the key (itemPreset).
I'm having trouble assigning the reusable cells to their sections.
The cells keep repeating themselves with the same text value in each cell.
The amount of rows per cell is correct and the section header title is correct.
Here is my code -
var subCategories = [SubCategoryCellInfo]()
var sectionsArray = [String]()
func querySections() -> [String] {
for selection in subCategories {
let subCategory = selection.itemPreset
sectionsArray.append(subCategory ?? "")
}
let uniqueSectionsArray = Set(sectionsArray).sorted()
return uniqueSectionsArray
}
func queryItemPreset(section:Int) -> [Int] {
var sectionItems = [Int]()
for selection in subCategories {
let itemPreset = selection.itemPreset
if itemPreset == querySections()[section] {
sectionItems.append(querySections().count)
}
}
return sectionItems
}
func numberOfSections(in tableView: UITableView) -> Int {
return querySections().count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return querySections()[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering(){
return filtered.count
}
return queryItemPreset(section: section).count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let subCell = tableView.dequeueReusableCell(withIdentifier: "subCell", for: indexPath) as! SubCategoryTableViewCell
let section = queryItemPreset(section: indexPath.section)
let task = section[indexPath.row]
let sub: SubCategoryCellInfo
if isFiltering(){
sub = filtered[task]
}
else{
sub = subCategories[task]
}
subCell.nameOfLocationText.text = sub.itemPreset
return subCell
}
SubCategoryCellInfo:
class SubCategoryCellInfo{
var itemPreset: String?
init(itemPreset:String?){
self.itemPreset = itemPreset
}
}
Solution: I grouped the array into sections based on itemPreset and then used that section
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let subCell = tableView.dequeueReusableCell(withIdentifier: "subCell", for: indexPath) as! SubCategoryTableViewCell
let groupedDictionary = Dictionary(grouping: subCategories) { (person) -> String in
return person.itemPreset ?? ""
}
var grouped = [[SubCategoryCellInfo]]()
let keys = groupedDictionary.keys.sorted()
keys.forEach { (key) in
grouped.append(groupedDictionary[key]!)
}
let task = grouped[indexPath.section]
let sub: SubCategoryCellInfo
if isFiltering(){
sub = filtered[indexPath.row]
}
else{
sub = task[indexPath.row]
}
subCell.nameOfLocationText.text = sub.itemPreset
return subCell
}