我正在尝试构建一个简单的应用程序,但令人惊讶的是,我找不到任何对我有帮助的答案。
根视图将是一个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": ""
],
]
]
]
]
例如,在这里,我希望创建一个名为“函数”的TableViewController,其中一个TableViewCell为“ Plan Leg”,并通过3个单元格“ Heading&Groundspeed”,“ Time&Distance”和“ Fuel&距离”
答案 0 :(得分:1)
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
中的就像相同的代码一样填充表格视图