tôi ở đâyCodable
的帮助下从JSON
获取数据并加载到TableView
中。在这里,我收到 JSON multiple array
,每个数组都有不同的键名称。我在 phần
的 tableview 中显示的键名。现在,问题是 JSON 数组显示了正确的顺序列表,但由于 dictionary
存储,我在 tableview 结果中得到了 unordered
列表。我需要显示相同的 order
,即 JSON 显示。
可编码
struct Root : Decodable {
let status : Bool
let sections : [Section]
private enum CodingKeys : String, CodingKey { case status, data }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
status = try container.decode(Bool.self, forKey: .status)
let data = try container.decode([String:[Result]].self, forKey: .data)
//sections = data.map{ Section(title: $0.key, result: $0.value) }
sections = data.compactMap{ return $0.value.isEmpty ? nil : Section(title: $0.key, result: $0.value) }
}
}
struct Section {
let title : String
var result : [Result]
}
struct Result : Decodable {
let id, name, date : String
let group : [String]
}
表格 View
// MARK: UITableview Delegates
func numberOfSections(in tableView: UITableView) -> Int {
return isFiltering ? filteredSections.count : sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let currentSection = isFiltering ? filteredSections[section] : sections[section]
return currentSection.result.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return isFiltering ? filteredSections[section].title : sections[section].title
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! MyCustomCell
let section = isFiltering ? filteredSections[indexPath.section] : sections[indexPath.section]
let item = section.result[indexPath.row]
cell.nameLabel.text = item.name
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//print("You tapped cell number \(indexPath.row).")
let section = isFiltering ? filteredSections[indexPath.section] : sections[indexPath.section]
let item = section.result[indexPath.row]
print("\(item)")
}
您不能对键进行排序,但可以定义键顺序
let keyOrder = ["Overdue", "Today", "Tomorrow", "Nextweek", "Future"]
struct Root : Decodable {
let status : Bool
let sections : [Section]
private enum CodingKeys : String, CodingKey { case status, data }
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
status = try container.decode(Bool.self, forKey: .status)
let data = try container.decode([String:[Result]].self, forKey: .data)
sections = keyOrder.compactMap({ key -> Section? in
guard let section = data[key], !section.isEmpty else { return nil }
return Section(title: key, result: section)
})
}
}
您的 TableView 数据源和委托(delegate)方法看起来很熟悉
Tôi là một lập trình viên xuất sắc, rất giỏi!