【问题标题】:How can I put Json data to the UITableView using Swift 4?如何使用 Swift 4 将 Json 数据放入 UITableView?
【发布时间】:2019-07-01 01:58:31
【问题描述】:

我这里有这样的结构:

struct Excercise: Codable {
    let excerciseID: String
    let excerciseName: String
    let description: String
    let intensity: Int
}

那么,这就是 var:

var excercistList = [Excercise]()

还有cellforrowat:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ExcerciseCell", for: indexPath)
    cell.textLabel?.text = self.excercistList[indexPath.row].excerciseName
    return cell
}

这就是 URLSession:

 URLSession.shared.dataTask(with: url) { (data, response, err) in
                        guard let data = data else{return}

   do {
         let excerciseList = try JSONDecoder().decode(Excercise.self, from: data)
         print(excerciseList.excerciseName)
      } catch let jsonErr {
           print("Error", jsonErr)
      }
  }.resume()

我在打印上得到了正确的结果,但在桌面上什么都没有。

我做错了什么?

【问题讨论】:

  • 数组是否填充了您想要的数据? print(excerciseList.excerciseName) numberOfRowsInSection 方法。
  • 填充数组后,您的表中需要一个 reloadData。
  • 你拿到数组后有没有给tableView.reloadData()打电话?
  • reloadData 可以帮到你。

标签: ios json uitableview swift4


【解决方案1】:

首先,您必须填写您的dataSource,即var excercistList = [Excercise]()。之后你必须重新加载tableView

URLSession.shared.dataTask(with: url) { (data, response, err) in
                        guard let data = data else{return}

   do {
         let excerciseListFromDecoder = try JSONDecoder().decode(Excercise.self, from: data)
        self.excercistList =  excerciseListFromDecoder
        self.tableView.reloadData()
      } catch let jsonErr {
           print("Error", jsonErr)
      }
  }.resume()

你必须确保你设置正确

tableView.delegate = self
tableView.dataSource = self

还有numberOfRowsInSection

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.excercistList.count
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2015-11-16
    • 2019-12-21
    相关资源
    最近更新 更多