swift 如何在可可荚折线图的字符串值中使用日期?

xesrikrc  于 2023-01-08  发布在  Swift
关注(0)|答案(1)|浏览(92)

这是我在折线图上得到x和y值的代码。

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]

我可以将这些日期值更改为字符串或使用dateFormatter格式化它们,并在x轴上看到它们作为真实的日期吗?如何做到这一点?
这是我在图表上看到的

ymdaylpp

ymdaylpp1#

我通过将这些行添加到委托方法中解决了问题

func didGetTimeframeRates(_ timeFrameRates: [String : Double]) {
             
             let sortedRates = timeFrameRates.sorted(by: {$0 < $1})
             let keys = sortedRates.map({$0.key})
             let values = sortedRates.map({$0.value})
             entries = []
             
             for item in 0..<keys.count {
                 entries.append(ChartDataEntry(x: Double(item), y: values[item]))
             }

相关问题