问题描述
我正在使用iOS Charts,并且在x轴上有重复的标签。
我收到许多答案(first,second,third),我应该设置粒度设置:
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()
我创建了一个自定义类,用于根据documentation的建议对传递到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并在图表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”上将两个图重叠在一起。
我正在使用enumerated()
提取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)
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)