簡體   English   中英

如何使用 Swift 4 將 Json 數據放入 UITableView?

[英]How can I put Json data to the UITableView using Swift 4?

我在這里有這樣的結構:

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()

我在印刷品上得到了正確的結果,但桌子上什么也沒有。

我究竟做錯了什么?

首先,您必須填充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
    }

暫無
暫無

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

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