簡體   English   中英

如何從 JSON 創建 Tableview 層次結構?

[英]How to create Tableview hierarchy from JSON?

我正在嘗試構建一個簡單的應用程序,但令人驚訝的是我找不到任何幫助我的答案。

根視圖將是一個 UINavigationController,在其中,我想放置一個 UITableViewController,我將使用字典中的數據填充 UITableViewCells。 當我點擊其中一個 UITableViewCell 時,它也會將我重定向到另一個從我的字典中填充的 UITableViewController。

[
        "name": "Functions",
        "icon": "calculator",
        "subcategories": [
            [
                "name": "Plan Leg",
                "icon": "globe",
                "subcategories": [
                    [
                        "name": "Heading & Groundspeed",
                        "destination": ""
                    ],
                    [
                        "name": "Time & Distance",
                        "destination": ""
                    ],
                    [
                        "name": "Fuel & Distance",
                        "destination": ""
                    ],
                ]
            ]
       ]
]

例如在這里,我很想創建一個名為“Functions”的 TableViewController,其中一個 TableViewCell“Plan Leg”重定向到另一個 TableViewController,其中包含 3 個單元格“Heading & Groundspeed”、“Time & Distance”和“Fuel & Distance”

class CatagoriesArray : Decodable {
    var catagories : [Catagories]?
}
class Catagories : Decodable {
    var name : String?
    var icon : String? 
    var subcategories : [Subcategories]?
}

class Subcategories : Decodable {
    var name : String? 
    var icon : String? 
    var subcategories : [SubcategoriesType]?
 }

 class SubcategoriesType : Decodable {
    var name : String? 
    var destination : String?
 }

添加這一行進行解碼

 let model = try? JSONDecoder().decode(CatagoriesArray.self, from: data) // data that will come from API response 

在“函數”tableViewController 中

override func viewDidLoad() {
    self.title = model[0].name // prints "Functions"
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return model[0].subcategories.count 
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) 
    cell.nameLabel.text = model[0].subcategories.name
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = self.storyBoard.instantiateViewController(withIdentifier : "identifier") as! FuncCatagory
    vc.subcategories = model[0].subcategories[indexPath.row]
    self.navigationController.pushViewController(vc, animated : true)
}

FuncCatagory填充 tableview 就像相同的代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM