How to group tableview cells based on field in JSON array

前端 未结 2 1528
半阙折子戏
半阙折子戏 2021-01-28 03:36

Essentially I have am using JSON data to create an array and form a tableview.

I would like the table cells to be grouped by one of the fields from the JSON array.

2条回答
  •  我在风中等你
    2021-01-28 04:26

    You can group a sequence based on a particular key using one of the Dictionary initializer,

    init(grouping:by:)
    

    The above method init will group the given sequence based on the key you'll provide in its closure.

    Also, for parsing such kind of JSON, you can easily use Codable instead of manually doing all the work.

    So, for that first make StockCustomer conform to Codable protocol.

    class StockCustomer: Codable {
        var customer: String?
        var number: String?
    }
    

    Next you can parse the array like:

    func parseJSON(data: Data) {
        do {
            let items = try JSONDecoder().decode([StockCustomer].self, from: data)
            //Grouping the data based on customer
            let groupedDict = Dictionary(grouping: items) { $0.customer } //groupedDict is of type - [String? : [StockCustomer]]
            self.feedItems = Array(groupedDict.values)
        } catch {
            print(error.localizedDescription)
        }
    }
    

    Read about init(grouping:by:) in detail here: https://developer.apple.com/documentation/swift/dictionary/3127163-init

    Make the feedItems object in CustomerViewController of type [[StockCustomer]]

    Now, you can implement UITableViewDataSource methods as:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.feedItems.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customerGoods", for: indexPath) as! CheckableTableViewCell
        let items = self.feedItems[indexPath.row]
        cell.textLabel?.text = items.compactMap({$0.number}).joined(separator: " - ")
        //Configure the cell as per your requirement
        return cell
    }
    

    Try implementing the approach with all the bits and pieces and let me know in case you face any issues.

提交回复
热议问题