Sectioning a tableview by dates from a dictionary

后端 未结 2 817
庸人自扰
庸人自扰 2021-01-26 11:57

I have a dictionary that contains a key/value pair of a Date that contains an array of my custom object Meals grouped together by the same dates.

Meal Object:

         


        
2条回答
  •  感动是毒
    2021-01-26 12:26

    Create a struct for the sections

    struct Section {
        let date : Date
        let meals : [Meal]
    }
    

    and map the grouped dictionary to an array of Section

    var sections = [Section]()
    
    let sortedDates = self.grouped.keys.sorted(>)
    sections = sortedDates.map{Section(date: $0, meals: self.grouped[$0]!)}
    

    You could add a date formatter to display the Date instance more meaningful.

    The table view data source methods are

    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {        
        return sections[section].date.description
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].meals.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "foodCell", for: indexPath)
        let meal = sections[indexPath.section].meals[indexPath.row]
        ...
    

    Note:

    Consider to use less optionals and a struct rather than a NSObject subclass. Unlike NSCoding Codable does not require to conform to NSObjectProtocol. And never declare properties as implicit unwrapped optional.

提交回复
热议问题