我创建一个简单的游戏,并希望创造一个选择屏幕。作为一种方法来保存所有的水平我创建了一个JSON文件。我现在尝试来用JSON文件级别的表视图。
[
{
"name": "animals",
"levels": [
{"start": "cat", "end": "bat"},
{"start": "dog", "end": "pig"}
]
},
{
"name": "foods",
"levels": [
{"start": "grape", "end": "apple"}
]
}
]
我已经能够成功地填充基于阵列上,如下所示的表格,但无法弄清楚如何从一个JSON文件做到这一点。
import UIKit
var test = ["hello", "world"]
class PackTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return test.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = test[indexPath.row]
return cell
}
}
我想填充这个JSON文件表视图,实现显示的名称的表:
动物 餐饮
谢谢!
相当容易:
外部类中创建两个结构
struct Item: Decodable {
let name: String
let levels : [Level]
}
struct Level: Decodable {
let start, end: String
}
与类中的数据源阵列
var items = [Item]()
在viewDidLoad
解码JSON假设包中的文件被命名为items.json
override func viewDidLoad() {
super.viewDidLoad()
do {
let data = try Data(contentsOf: Bundle.main.url(forResource: "items", withExtension: "json")!)
items = try JSONDecoder().decode([Item].self, from: data)
tableView.reloadData()
} catch { print(error) }
}
您可以删除numberOfSections
因为默认是1
,其他方法
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = items[indexPath.row].name
// do something with items[indexPath.row].levels
return cell
}
要填充与本地JSON文件的tableview,所以这里是简单和容易的答案,你只需要检查出来,
http://vasundharavision.com/blog/ios/how-to-parse-json-from-File-and-url-in-swift-4-2
我希望这个对你有用。