简体   繁体   中英

Swift UITableView (no sections) filter to table view with sections

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 AZ)

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
}

It's all in your data model. You always have sections with rows. But you only have one section. Modify your data model and your data source methods to always support multiple sections. Just sometimes this data model will only have one section.

Update your data model to be an array of dictionary where the dictionary contains a title and an array. The top level array is your sections (may just be one at times). The inner arrays (in each dictionary) are the rows of each section. Or define a struct with a title and array instead of using a dictionary.

With this in place, and your table view data source and delegate methods written to always work with multiple sections, your table will also work just fine when you happen to have just one section worth of data.

Now it's just a matter of populating your array of dictionary as needed depending on how you wish to organize the data for display.

To answer the question of section headers. You could try using:

tableView(_ tableView: UITableView, titleForHeaderInSection section: Int)

or

tableView(tableView: UITableView, viewForHeaderInSection section: Int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM