Loroa Loroa - 2 months ago 23
iOS Question

UITableView sections from JSON data swift

I have JSON data like this:

[{"name":"Rice","Menu":{"title":"titl1"}},{"name":"Name2","Menu":{"title":"title2"}}]


I want to build a table view with a section for each pair [id, name]. The section title should be the menu title, the only cell for each section should be the name value.

How can I parse the JSON data into an array and use in order to array.count determine how many section have to be displayed?

EDIT

class Menus{
private var _name:String!
private var _title:String!

var name:String{
return _name
}

var title:String{
return _title
}


init(nam:String, title:String){
_name = nam
_title = title
}
}

Answer
var arrData:[[String:AnyObject]]! = [
    ["name":"Rice",
        "Menu":
            [
                "title":"titl1"
        ]
    ],
    [
        "name":"Name2",
        "Menu":
            [
                "title":"title2"
        ]
    ]
]

var arrMenu:[Menus]! = []

override func viewDidLoad() {
    super.viewDidLoad()

    for i in 0..<arrData.count {
        let dish = arrData[i]
        let menu = dish["Menu"] as! [String:String]

        let name = dish["name"] as! String
        let title = menu["title"]

        arrMenu.append(Menus.init(nam: name, title: title!))
    }


}
// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return arrMenu.count
}

override func tableView( tableView :UITableView, titleForHeaderInSection section: Int)->String{
    let menu:Menus = arrMenu[section]
    return menu.name
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    let menu = arrMenu[indexPath.section]

    cell.textLabel?.text = menu.title

    return cell
}
Comments