swift - 在 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
我真的很困惑如何解决这个问题
解决方案
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()
}
推荐阅读
- python - 如何用 python 中的 pandas 数据框对象替换 salesforce 对象?
- python - tkinter 无法弄清楚如何从文件中读取并输入文本输入
- javascript - 如何在角度 8 中将事件从一个父组件传递到子组件?
- angular - 角度日期选择器选择周
- java - 我们可以在java中的一个类中有多个静态锁吗
- javascript - 在 Magento-2 中,如何编辑带有值的订单摘要标签并在购物车页面中添加更多标签?
- ffmpeg - FFMPEG 分段无线电流在连接后显示不正确的持续时间
- java - 写一个java方法读取一个json文件,写成toml文件
- php - 传递给 Symfony\Component\VarDumper\Dumper\HtmlDumper::setDumpHeader() 的参数 1 必须是字符串类型,给定 null
- database - TDengine如何检查数据库参数修改是否生效