You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据JSON数据的date字段分组填充TableView的分区与行?

没问题,我来带你搞定这个按日期分组显示TableView的需求,咱们从数据处理到TableView实现一步步来:

1. 先定义数据模型

首先把JSON里的字段映射成一个模型对象,这样操作数据会更清晰(以Swift为例,OC思路类似):

struct Match: Codable {
    let id: String
    let date: String
    let title: String
}

这个模型遵循Codable协议,方便直接用JSONDecoder解析JSON数据。

2. 解析JSON并按日期分组

拿到JSON数据后,先解析成Match数组,再按date字段分组,同时对分组的日期进行排序,保证分区顺序是合理的:

// 假设你已经获取到JSON对应的Data对象(比如从网络请求或者本地文件读取)
do {
    // 解析JSON,取出upcoming数组
    let response = try JSONDecoder().decode([String: [Match]].self, from: jsonData)
    let matches = response["upcoming"] ?? []
    
    // 按date字段分组,得到key为日期、value为对应Match数组的字典
    let groupedMatches = Dictionary(grouping: matches, by: { $0.date })
    
    // 对日期key进行排序,确保分区按时间顺序展示
    self.sortedDates = groupedMatches.keys.sorted()
    
    // 保存分组后的数据,作为TableView的数据源
    self.groupedData = groupedMatches
} catch {
    print("JSON解析出错:\(error.localizedDescription)")
}

这里需要在ViewController里定义两个属性:

var sortedDates: [String] = [] // 存储排序后的日期,用来确定分区顺序
var groupedData: [String: [Match]] = [:] // 存储每个日期对应的Match列表
3. 实现TableView的数据源方法

接下来就是实现UITableViewDataSource的核心方法,把分组后的数据绑定到TableView上:

3.1 返回分区数量

func numberOfSections(in tableView: UITableView) -> Int {
    return sortedDates.count
}

3.2 设置分区标题

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sortedDates[section]
}

3.3 返回每个分区的行数

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let currentDate = sortedDates[section]
    return groupedData[currentDate]?.count ?? 0
}

3.4 配置单元格内容

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // 这里假设你已经注册了复用标识符为"MatchCell"的单元格
    let cell = tableView.dequeueReusableCell(withIdentifier: "MatchCell", for: indexPath)
    
    let currentDate = sortedDates[indexPath.section]
    guard let currentMatch = groupedData[currentDate]?[indexPath.row] else {
        return cell
    }
    
    // 给单元格赋值,比如主标题显示球队名称,副标题显示ID
    cell.textLabel?.text = currentMatch.title
    cell.detailTextLabel?.text = "ID: \(currentMatch.id)"
    
    return cell
}
额外优化提示

如果你的需求是按日期(忽略时间)分组,而不是精确到时分的分组,那需要先对date字符串做格式化处理,提取年月日部分:

// 定义一个格式化日期的工具方法
func extractDatePart(from dateString: String) -> String {
    let inputFormatter = DateFormatter()
    inputFormatter.dateFormat = "yyyy/MM/dd HH:mm"
    
    guard let date = inputFormatter.date(from: dateString) else {
        return dateString
    }
    
    let outputFormatter = DateFormatter()
    outputFormatter.dateFormat = "yyyy/MM/dd"
    return outputFormatter.string(from: date)
}

然后分组的时候用处理后的日期:

let groupedMatches = Dictionary(grouping: matches, by: { extractDatePart(from: $0.date) })

内容的提问来源于stack exchange,提问作者user3891083

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:25:34