Reputation: 15022
I'm new to Swift, and not good at manipulating json and hash.
Here's my JSON [Array of Users]
[
{"name": "mary", "age": 24, "detail": "i love ..."},
{"name": "mark", "age": 28, "detail": "i love ..."}
]
I want to show each user's name first and then their age
And If you click there name or age, it will show the detail
I only know how to iterate a array and puts the value on the cell.
Like this way, but now knowing how to display tablecells with a dictionary
cell.textLabel.text = self.items[indexPath.row]
How could I know which key
should I use in each loop ?
func tableView(invoice: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
How could I know this time, I should use the name
, and next time I should use age
to show my cell?
Upvotes: 0
Views: 100
Reputation: 723
Since your original JSON is an array, you can parse the JSON elements in a dictionary and then use it in your cell.
func parseJSONArray(jsonData: NSData) -> Array<NSDictionary>{
var error: NSError?
var usersDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as Array<NSDictionary>
return usersDictionary
}
Then you can use this usersDictionary to get your users info:
cell.textlabel.text = usersDictionary[indexPath.row].valueForKey("name")
For the logic of key decision, try something like below:
var index = indexPath.row/2;
var key = indexPath.row%2;
if (key == 0) { //show the name cell
cell.textlabel.text = usersDictionary[index].valueForKey("name")
} else { //show the age cell
cell.textlabel.text = "Age " + usersDictionary[index].valueForKey("age")
}
Similar logic for cell font style and color can be used by you. Its not very complex. Just make sure to have number of rows as twice the json array size (1 cell for each key) and also proper logic for cell selected method.
Upvotes: 1
Reputation: 5148
try this code, because name is show in even cell, age show in odd
var index = indexPath.row/2;
var isAgeCell = indexPath.row%2
if (isAgeCell == 0) {
cell.textLabel.text = self.items[index]["name"]
}
else {
cell.textLabel.text = self.items[index]["age"]
}
Upvotes: 0