Populating TableView with multiple sections and multiple dictionary in an array in Swift

前端 未结 2 1922
独厮守ぢ
独厮守ぢ 2020-12-07 23:40

I have a 3 category which I was using as a section. In that section I have to populate data which is in array of dictionary. Here is my code:-

var sections =         


        
2条回答
  •  情深已故
    2020-12-08 00:25

    Use a custom struct

    struct Category {
       let name : String
       var items : [[String:Any]]
    }
    

    var sections = [Category]()
    
    let itemsA = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]
    let itemsB = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]
    let itemsC = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]
    
    
    sections = [Category(name:"A", items:itemsA), 
                Category(name:"B", items:itemsB), 
                Category(name:"C", items:itemsC)]
    

    func numberOfSections(in tableView: UITableView) -> Int {
        return self.sections.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sections[section].name
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let items = self.sections[section].items
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "StoreCell") as! UITableViewCell
        let items = self.sections[indexPath.section].items
        let item = items[indexPath.row]
        print(item["ItemId"] as? String)
    
        return cell
    }
    

    You can still improve the code if you are using a custom struct also for the dictionaries.

提交回复
热议问题