I have a list of custom objects [Species] displayed in the table view, which is sorted alphabetically. Table has one section with no headers, it's one continuous list.
What I would like to achieve is, when a user selects the option to sort the data "by country", to do the following:
- to sort array to find out how many sections I will need by - "Species.country"
- to create sections with header titles of the country
- to sort countries (Sections) alphabetically
- reload table view to display sections
- remove sections on the reversed action (sort entire list A-Z)
Is it possible to create dynamically sections when filtering/sorting? Can you please point me the right direction? Many thanks A.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.genusArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CustomMenuCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomMenuCell
//genusArr is type of [Species]
let genus = self.genusArr[indexPath.row]
cell.populate(with: genus)
return cell
}
To answer the question of section headers. You could try using:
tableView(_ tableView: UITableView, titleForHeaderInSection section: Int)
or
tableView(tableView: UITableView, viewForHeaderInSection section: Int)