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

如何在CocoaPods折线图中将X轴时间戳转为可读日期字符串?

解决Swift中Charts折线图X轴时间戳转可读日期的问题

我在Swift项目中通过CocoaPods使用折线图,现有代码将日期字符串转为时间戳作为ChartDataEntry的X轴数据,当前图表X轴显示的是时间戳,希望转为经DateFormatter格式化的可读日期字符串,请问该如何实现?

现有代码

extension ViewController: CurrencyManagerDelegate {
     
     func didFailWithError(error: Error) {
     print(error)
     }
         func didGetTimeframeRates(_ timeFrameRates: [String : Double]) {
             
             let sortedRates = timeFrameRates.sorted(by: {$0 < $1})
             let keys = sortedRates.map {(self.formatter.date(from: $0.key)!.timeIntervalSince1970 as Double)}
             let values = sortedRates.map({$0.value})
             entries = []
             
             for item in 0..<keys.count {
                 entries.append(ChartDataEntry(x: keys[item], y: values[item]))
             }
             
             let set = LineChartDataSet(entries: entries, label: "Line Chart")
              
             set.colors = ChartColorTemplates.joyful()
              
             let data = LineChartData(dataSet: set)
             lineChart.data = data
             DispatchQueue.main.async {
                 self.lineChart.notifyDataSetChanged()
             }
         }
}

控制台输出

[ChartDataEntry, x: 1671656400.0, y 19.803011, ChartDataEntry, x: 1671742800.0, y 19.907873, ChartDataEntry, x: 1671829200.0, y 19.912121, ChartDataEntry, x: 1671915600.0, y 19.901387, ChartDataEntry, x: 1672002000.0, y 19.855934, ChartDataEntry, x: 1672088400.0, y 19.850483, ChartDataEntry, x: 1672174800.0, y 19.886824, ChartDataEntry, x: 1672261200.0, y 19.951368, ChartDataEntry, x: 1672347600.0, y 20.04376, ChartDataEntry, x: 1672434000.0, y 20.04376]

当前图表效果

折线图X轴显示的是纯数字时间戳,无法直观识别日期信息。


实现方案

要实现X轴显示格式化日期,需要自定义IAxisValueFormatter处理时间戳转日期的逻辑,步骤如下:

1. 自定义X轴日期格式化器

创建遵循IAxisValueFormatter协议的类,在方法内将时间戳转换为指定格式的日期字符串:

class DateAxisValueFormatter: NSObject, IAxisValueFormatter {
    private let dateFormatter: DateFormatter
    
    init(dateFormatter: DateFormatter) {
        self.dateFormatter = dateFormatter
        super.init()
    }
    
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        let date = Date(timeIntervalSince1970: value)
        return dateFormatter.string(from: date)
    }
}

2. 配置折线图X轴

在原有数据处理代码中,添加X轴的格式化配置:

func didGetTimeframeRates(_ timeFrameRates: [String : Double]) {
    // 原有数据处理逻辑保持不变
    let sortedRates = timeFrameRates.sorted(by: {$0 < $1})
    let keys = sortedRates.map {(self.formatter.date(from: $0.key)!.timeIntervalSince1970 as Double)}
    let values = sortedRates.map({$0.value})
    entries = []
    
    for item in 0..<keys.count {
        entries.append(ChartDataEntry(x: keys[item], y: values[item]))
    }
    
    let set = LineChartDataSet(entries: entries, label: "Line Chart")
    set.colors = ChartColorTemplates.joyful()
    
    let data = LineChartData(dataSet: set)
    lineChart.data = data
    
    // 新增X轴配置
    let xAxis = lineChart.xAxis
    // 设置日期格式,可根据需求调整,比如"yyyy-MM-dd"、"MM-dd"等
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd"
    dateFormatter.locale = Locale.current
    // 绑定自定义格式化器
    xAxis.valueFormatter = DateAxisValueFormatter(dateFormatter: dateFormatter)
    // 可选:旋转标签避免重叠
    xAxis.labelRotationAngle = -45
    // 可选:设置X轴标签显示在底部
    xAxis.position = .bottom
    
    DispatchQueue.main.async {
        self.lineChart.notifyDataSetChanged()
    }
}

3. 注意事项

  • 确保原代码中解析日期字符串的formatter与自定义格式化器的locale、时区等设置一致,避免日期转换错误。
  • 如果X轴标签仍有重叠,可通过xAxis.setLabelCount(6, force: false)设置固定标签数量,或调整图表宽度优化显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:10:30