How to Fill Uitableview with a Data from Dictionary. Swift

How to fill UITableView with a data from Dictionary. Swift

I used a struct Rate to Reproduce your current Output

struct Rate {
var ask : Float?
var bid : Float?

static var shared = Rate()

mutating func initWithDictValues(_ currentRate : Rate) {
self.ask = currentRate.ask
self.bid = currentRate.bid
}
}

Currencies Array

/// Array Declaration
var currencies = [String:Any]()

/// Add Values
currencies = ["EUR":Rate(ask: 30.8500, bid: 30.8500),"USD":Rate(ask: 26.3000, bid: 26.3000),"RUB":Rate(ask: 0.4150, bid: 0.4150)]

Get All Keys in Separate Array so we can Dequeue cell Easily

var keysArray = Array(currencies.keys)

TableView Function

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

/// Get CurrentKey
let currentKey = keysArray[indexPath.row]
let currentIndexKey : Rate = currencies[currentKey] as! Rate

/// Assign Values
cell.currencyLabel.text = currentKey
cell.askLabel.text = currentIndexKey.ask ?? 0
cell.bidLabel.text = currentIndexKey.bid ?? 0

return cell
}

Playground Output

Sample Image

Hope this helps

Swift - Populate uitableview with dictionary of [String: [String: String]]

Rather than using an array of dictionaries, you should consider using objects that better represent your data.

struct Question: {
let question: String
let answer: String
}

struct DiaryDay {
let date: Date // Note this is a Date object, not a String
let questions: [Question]
}

then you have

let diaryDays = DiaryDay(date: <date>, questions: 
[Question(question: "question1": answer: "answer"),
Question(question: "question2": answer: "answer")])

while there's a bit more code, going forward you'll find it easier to see what's happening.

It looks like you should have a section per diary day…

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

and then one row per question…

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let diaryDay = diaryDays[section]
return diaryDay.questions.count
}

and then configure your cell…

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// dequeue cell
let diaryDay = diaryDays[indexPath.section]
let question = diaryDay.questions[indexPath.row]
cell.question = question
return cell
}

and show the date in the section header…

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let diaryDay = diaryDays[section]

return // formatted diaryDay.date
}

How do I populate a tableView with all the data in a dictionary?

A tableView displays stuff in order. A dictionary isn't ordered. By looping over your dictionary with "for (key, value) in clubDict" you will only get the last entry in the dictionary to be displayed.

What you have to do is get the unordered dictionary into an ordered form like an array. For example like so:

let dict = ["key1" : "value1"]; // Your dictionary. Use the one you already have
var arr : [(String, String)] = [];
for (key, value) in dict {
arr.append((key, value));
}

Then you will have to adjust the "numberOfRowsInSection" method to now use arr.count

For each cell the cellForRowAtIndexPath method will be called.
There you extract the correct entry from the array by its index:

let (key, value) = arr[indexPath.row]; //read element for the desired cell
cell.textLabel?.text = key
cell.detailTextLabel?.text = value.address

You have to adjust the datatypes to your needs. I just took a dictionary of String:String

Using a dictionary to populate a UITableView data in Swift 4

You can use contactDictionary.keys to retrieve the array of keys and use the key to find value, but the order may change every time; Swift does not guarantee the order of dictionary. If order is important, you can search for 3rd party OrderedDictionary or other data structures.

Fill the Tableview with Array of Dictionary and separating by section

The best solution is to map the dictionaries to custom structs, but if you want to keep this data model the table view data source methods are

var selectedVariation = [["ice": 20, "cold": 30], ["no Choco": 0, "with Choco": 40]]

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

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
selectedVariation[section].count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "VariationCell", for: indexPath) as! VariationTableViewCell
let section = selectedVariation[indexPath.section]
let key = section.keys.sorted()[indexPath.row]
let value = section[key]!
cell.variationName.text = key
cell.variationPrice.text = "+" + String(value)
return cell
}

Note: func numberOfSectionsInTableView(tableView: UITableView) -> Int is Swift 2

How to populate tableview with dictionary key-values?

Declare userData as array. Replace

@Published var userData: [String:Int] = [:]

with

@Published var userData: [String] = []

and assign the dictionary keys to the array

self.userData = Array(dataFromJson.keys)

In cellForRow display the item at given index

cell.textLabel!.text = userData[indexPath.row]

Populating a UITableView with data from a dictionary

Because you can never guarantee that your dictionary contents will come out in the same order it went in, you cannot do it directly from a dictionary. Therefore you would need to do it indirectly using a separate array that is based on the dictionary keys (for example).

One such way of doing this would be to create an array based on the sorted keys of the dictionary thusly:

sortedKeys = Array(dictionary.keys).sorted(<)

Then in your UITableView delegate/data-source methods use indexPath.row as index to the sortedKeys array to grab a key the array. Then use that key, to grab the value from your dictionary.



Related Topics



Leave a reply



Submit