Ken
Ken

Reputation: 55

Populate the section array to UITableview section

I have a list of JSON data:

({
    "id" = 1;
    "name" = "lemon tea";
    "date" = 20180820;
    "daycount" = 1;
})

Model:

class OrderItemModal: NSObject {
    var id: String!
    var name: String!
    var date: Date!
    var daycount: String!
}

Please read the swift file below:

(DownloadOrderModal.swift):

protocol OrderDownloadProtocol: class {
    func itemsDownload(items: Array<Any>)
}    
...
let bmsOrders = NSMutableArray()
...

weak var delegate: OrderDownloadProtocol!
let urlPath = "http://localhost/production/api/db_orders.php"

func downloadItems() {
    let url = URL(string: urlPath)!
    let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
...

    for i in 0..<jsonResult.count
    {
        jsonElement = jsonResult[i] as! NSDictionary
        let bmsOrder = OrderItemModal()
....
bmsOrders.add(bmsOrder)
....

(tableview Controller)

    struct Objects {
    var sectionName: String!
    var sectionObjects: Array<Any>!
}

var sectionArray = [Objects]()

func itemsDownload(items: Array<Any>) {
    orderItems = items as! [OrderItemModal]
    for item in orderItems {
        sectionArray += [Objects(sectionName: item. daycount, sectionObjects: item.description)]
    }
}

Number of Section:

return daysSection.count

TableViewCell:

sectionArray[indexPath.section].sectionObjects[indexPath.row] as! OrderItemModal

TableViewTitle:

return sectionArray[section].sectionName

numberOfRowsInSection:

sectionArray[section].sectionObjects.count

... let sectionItems = groupItem[indexPath.section] let items = sectionItems[indexPath.row]

for element in items.sectionObjects {
let item = element as! OrderItemModal
cell.name?.text = item.name

So the app now run okay

Upvotes: 0

Views: 148

Answers (1)

Deepika
Deepika

Reputation: 468

From the look of it feels that you are using the wrong data source in your func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath). You are using orderItems which has all the data you received.

As I understand from generateDayDict(), you have just segregated your orderItems to calculate your sections. You should be segregating your orderItems as well to push them as values in respective dictionaries( or however you would want to manage your datasource) so that rows pick up the right model object.

I would have created a dictionary with key names as sections and values as array of OrderItemModal which will represent respective rows in UITableView

Upvotes: 1

Related Questions