json - 如何在 swift 中根据段在 tableview 中显示 JSON 响应
问题描述
我在视图控制器中有树段调用。OPEN, CLOSED, ALL
我的 JSON 响应如下:
{
"jsonrpc": "2.0",
"result": {
"data": {
"open": [
{
"user_id": "10",
"request_title": "Title-2",
"category": "4",
"gender": "M",
"location": "On earth",
"from_date": "2021-04-09",
}
{
"user_id": "10",
"request_title": "Title-2",
"category": "4",
"gender": "M",
"location": "On earth",
"from_date": "2021-04-09",
}
........
]
"close": [
{
"user_id": "10",
"request_title": "Title-2",
"category": "4",
"gender": "M",
"location": "On earth",
"from_date": "2021-04-09",
}
........
]
"all": [
{
"user_id": "10",
"request_title": "Title-2",
"category": "4",
"gender": "M",
"location": "On earth",
"from_date": "2021-04-09",
}
{
"user_id": "10",
"request_title": "Title-2",
"category": "4",
"gender": "M",
"location": "On earth",
"from_date": "2021-04-09",
}
........
]
}
}
}
在这里,我能够获得 JSON 响应.. 并且在i am getting "open" values and adding them in
requestsArray to show in tableview.. but now this
requestsArray want to show in
open` 段下方,就像关闭段中的相同关闭值一样。如何做到这一点
if let code = ((resp.dict?["result"] as? [String : Any])){
let totalData = code["data"] as? [String : Any]
if let open = totalData?["open"] as? [[String : Any]]{
for (value) in open {
self?.title_req = value["request_title"] as? String
self?.gender = value["gender"] as? String
self?.location = value["location"] as? String
self?.requestsArray.append(AppliedRequestCellData(request_title: self?.title_req, gender: self?.gender, location: self?.location))
}
DispatchQueue.main.async {
self.tableView.reloadData()
} }
我的部分如下
hmSegment.indexChangeBlock = { index in
print("in index segment")
print(index)
if index == 0{
// here how to show JSON `open` response in tableview
}
if index == 1{
// here how to show JSON `close` response in tableview
}
if index == 2{
// here how to show JSON `all` response in tableview
}
}
请帮我用段在 tableviewview 中鞋 JSON 响应
解决方案
创建 4 个数组
var openItems = [AppliedRequestCellData]()
var closedItems = [AppliedRequestCellData]()
var allItems = [AppliedRequestCellData]()
var items = [AppliedRequestCellData]()
items
是主要的数据源数组。
解码 OPEN、CLOSED 和 ALL 的数据并将它们分配给相应的数组。
在indexChangeBlock
更改主数组的内容并重新加载表视图
hmSegment.indexChangeBlock = { index in
print("in index segment")
switch index {
case 0: self.items = self.openItems
case 1: self.items = self.closedItems
case 2: self.items = self.allItems
default: break
}
self.tableView.reloadData()
}
考虑使用UITableViewDiffableDataSource
它提供了一个很好的变化动画。
还考虑使用Codable
和JSONDecoder
推荐阅读
- r - R中的时间序列标签
- google-app-engine - Google Cloud Endpoints 和 App Engine 的延迟在 1 到 2 秒之间是否正常?
- python - Google Cloud ML-Engine 在线预测错误:为已包含的占位符张量提供值
- java - FileOutputStream try-with-resources 不关闭文件描述符
- django - 使用 UniqueConstraint 解决 Django admin 中的“get() 返回多个”错误
- sas - SAS,转置表
- c - 如何使用 OpenMP 并行化嵌套的 FOR 循环
- micronaut - 我可以将 Apache Camel 与 Micronaut 一起使用吗?
- sql - 如何在没有重复礼物的情况下计算礼物金额
- java - 在 Kotlin 中启用 CORS 时,Spark 在访问路由时返回空响应