如何基于本地json文件填充表格视图?

时间:2019-01-31 08:36:38

标签: arrays json swift uitableview tableview

我正在创建一个简单的游戏,并想要创建一个关卡选择屏幕。为了保存所有级别,我创建了一个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文件填充表格视图,以实现显示名称的表格:

动物
食物

谢谢!

2 个答案:

答案 0 :(得分:1)

非常简单:

在类外创建两个结构

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
}

答案 1 :(得分:0)

您想用本地json文件填充tableview,所以这是您只需将其签出的简单答案

http://vasundharavision.com/blog/ios/how-to-parse-json-from-File-and-url-in-swift-4-2

我希望它对您有用。

相关问题