我正在使用iOS Charts,我的x轴上出现了重复的标签。
我得到了许多答案(first, second, third),它们都建议我设置粒度设置:
但是,当我设置x轴标签时,它们会简单地消失。
这个想法是创建一个日期数组
我正在使用
![enter image description here](https://istack.dev59.com/Ogu6G.webp)
xAxis.granularityEnabled = true
xAxis.granularity = 1.0
但是,当我设置x轴标签时,它们会简单地消失。
我的 x 轴设置:
let xAxis = lineChartView.xAxis
xAxis.labelPosition = .bottom
xAxis.labelFont = .boldSystemFont(ofSize: 12)
xAxis.setLabelCount(6, force: false)
xAxis.labelTextColor = UIColor(red: 0, green: 0, blue: 255/255, alpha: 1.0)
xAxis.axisLineColor = UIColor(white: 0.2, alpha: 0.4)
xAxis.gridColor = UIColor(white: 0.8, alpha: 0.4)
xAxis.valueFormatter = ChartXAxisFormatter()
我根据文档的建议,创建了一个自定义类来格式化传递给x轴的值:
class ChartXAxisFormatter: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("MM/dd")
let date = Date(timeIntervalSince1970: value)
return dateFormatter.string(from: date)
}
}
更新
感谢 @aiwiguna 和 Charts repo 的帮助,我成功创建了一个自定义类,该类接收两个参数:日期(Double)和相应的索引(Int),而不仅仅是日期。
class ChartXAxisFormatter: NSObject, IAxisValueFormatter {
private var dates: [Double]?
convenience init(usingDates dateArr: [Double]) {
self.init()
self.dates = dateArr
}
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
print("value: \(value)")
print("dates: \(dates)")
let index = Int(value)
guard let dates = dates, index < dates.count else {
return "?"
}
let date = dates[index]
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("MM/dd")
let formattedDate = Date(timeIntervalSince1970: date.rounded())
return dateFormatter.string(from: formattedDate)
}
}
这个想法是创建一个日期数组
[1598409060.0, 1598409060.0]
,通过访问索引一个一个地返回它们。记录value
和index
可以证明这一点。问题在于,虽然重复标签的数量已经减少到与绘图数量匹配,但重复项仍然存在。
这两个图应该在同一X轴标签“8/25”上堆叠。我正在使用
枚举()
来提取ChartDataEntry
的索引:var dateArr = [Double]()
for (index, fetchedMetric) in fetchedMetrics.enumerated() {
let date = fetchedMetric.date.timeIntervalSince1970
dateArr.append(date)
if var yValues = metricDict[fetchedMetric.unit] {
yValues.append(ChartDataEntry(x: Double(index), y: Double(truncating: fetchedMetric.value)))
metricDict.updateValue(yValues, forKey: fetchedMetric.unit)
} else {
metricDict.updateValue([ChartDataEntry(x: Double(index), y: Double(truncating: fetchedMetric.value))], forKey: fetchedMetric.unit)
}
}