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

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 = [Category A, Category B, Category C]
var itemsA = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]
var itemsB = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]
var itemsC = [["Item": "item A","ItemId" : "1"],["Item": "item B","ItemId" : "2"],["Item": "item C","ItemId" : "3"]]

func numberOfSections(in tableView: UITableView) -> Int {
    return self.sections.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return self.sections[section]
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return ??
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "StoreCell") as! UITableViewCell
    ????
    ????
    return cell
}

The items array I need to populate into table category wise. If anyone can answer. Thank you!

Answers 1

  • If itemA array for Category A, itemB array for Category B and so on then you can return array count in numberOfRowsInSection this way.

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch (section) {
            case 0: 
               return itemsA.count
            case 1: 
               return itemsB.count
            default: 
               return itemsC.count
         }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "StoreCell") as! UITableViewCell
        switch (indexPath.section) {
            case 0: 
               //Access itemsA[indexPath.row]
            case 1: 
               //Access itemsB[indexPath.row]
            default: 
               //Access itemsC[indexPath.row]
         }
         return cell
    }
    

    Note: It is batter if you create single Array of struct or custom class that will reduce all your array with single array.


Related Articles