Denis Prozukin
Denis Prozukin

Reputation: 133

Configuring collectionView:cellForRowAt based on an array of strings

I've got this JSON data (not verbatim) that I get from the backend. It contains the actual data and an array of strings describing the sequence of cells to be shown:

{
    "data": [
        {
            "name": "text",
            "data": {
                "text": "some text"
            }
        },
        {
            "name": "pic",
            "data": {
                "url": "https://somepic.jpg",
                "text": "picture"
            }
        },
        {
            "name": "switcher",
            "data": {
                "id": 1,
                "options": [
                    {
                        "id": 0,
                        "text": "option 1"
                    },
                    {
                        "id": 1,
                        "text": "option 2"
                    },
                    {
                        "id": 2,
                        "text": "option 3"
                    }
                ]
            }
        }
    ],

    "view": [
        "text",
        "pic",
        "switcher",
        "text"
    ]
}

The problem is that I can't get my head around how to configure cellForRowAt: and get the right order of cells in one section. (i.e. text, pic, selector, text).

I tried a couple of things:

  1. Looping through "view" array and switching on each individual view string to dequeue a specific cell but that doesn't seem to work since returning a cell from a switch case gives a "unexpected non-void return value in void function" error.
  2. I was also thinking about turning a "view" array into a dictionary and then, based on keys in it, dequeue a specific cell but then again, a dictionary should have unique keys meaning that I will not have 2 "text" entries, one of them will be lost.

So, the questions is: how can I dequeue specific cells based on the array of strings? It's also important to understand that it should be done in one section. I'm feeling that it's somehow not that difficult to implement but I'm kinda lost right now. Thanks!

Upvotes: 0

Views: 69

Answers (1)

Ptit Xav
Ptit Xav

Reputation: 3219

you need to transform your view list and data array into an array of cell contents that you can use inside the TableViewDelegate and TableViewSource method :

var cellsContents : [Int] = []
for aView in view {
var found = false
var index = 0
for aData in data {
    if !found {
        if let name = aData["name"] as? String {
            if aView == name {
                found = true
                cellsContents.append(index)
                continue
            }
        }
        index = index + 1
    }
}

}

Then :

  • number of rows : cellsContents.count
  • type and contents for a row : data[cellsContents[indexPath.row]]["name"] and data[cellsContents[indexPath.row]]["data"]

Upvotes: 1

Related Questions