首页 > 解决方案 > 在 UITableView 中显示结构中的数据

问题描述

我想我在 Swift 4 中的表格视图方面遗漏了一些东西,或者我只是没有像我应该的那样传递我的数据。我读了一个我应该保存在结构“工作区”中的 json,然后我使用相同的结构在我的 tableview 中显示数据

我有这堂课:

public class User {

    var Wor = [Workspace]()
    var WorData = Workspace()

}

这个结构: getuserWorkspace 函数应该更新结构值。

struct Workspace: Decodable {
    var guid: String
    var name: String

private enum CodingKeys : String, CodingKey {
    case guid = "guid"
    case name = "name"
}

init(){
    self.guid = "guid"
    self.name = "name"
}

mutating func getUserWorkspace(base: String, completed: @escaping () -> ()){
    let url = URL(string: "SOME URL")!
    var request = URLRequest(url: url)
    request.addValue("Basic \(base)", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    URLSession.shared.dataTask(with: request){ (data, response, error) in
        if error == nil {
            do {
                let rep = try JSONDecoder().decode([Workspace].self, from: data!)
                print(rep) 
                //it prints exactly what I receive so I guess I'm saving it well? 
                DispatchQueue.main.async {
                    completed()
                }
            }catch {
                print(error)
            }
        }
    }.resume()
}

我的视图控制器中有这个:

   var co = User()

override func viewDidLoad() {
    super.viewDidLoad()

    co.getBase()
    co.WorData.getUserWorkspace(base: co.Base) {
        print("success")
        self.listView.reloadData()
        self.updateVertically()
    }
    print("guid " + co.WorData.guid)
    print("name " + co.WorData.name)
    print("work ", co.WorData)
    print("wor ", co.Wor)
    listView.delegate = self
    listView.dataSource = self
}

在我要返回的表格视图行co.Wor.count 中并且在单元格行中co.Wor[indexPath.row].name

但一切都是空白的,印刷品给了我这个:

guid guid
name name
work  Workspace(guid: "guid", name: "name")
wor  []
[Proj.Workspace(guid: "8a81b08e45467656fr467f51119047027", name: "test ok")]
(this print is inside the function in the structure)
success

我真的很困惑如何解决这个问题

标签: swifttableviewstructure

解决方案


1-最好设置dataSource和delegate topviewDidLoad

override func viewDidLoad() {
  super.viewDidLoad()
   listView.delegate = self
  listView.dataSource = self
}

2- 获取数据后分配数据

mutating func getUserWorkspace(base: String, completion: @escaping (_ arr:[Workspace]?) -> void ){
  let rep = try JSONDecoder().decode([Workspace].self, from: data!)
  completion(rep)
}

//

  co.WorData.getUserWorkspace(base: co.Base) { (arr) in 
    print("success")
    self.co.Wor = arr
    self.listView.reloadData()
    self.updateVertically()
}

推荐阅读