使用 iOS 图表框架保持 xAxis 值的顺序
Keep order of xAxis values using iOS Charts framework
我正在设置一个在 xAxis 上有一些值的 CombinedChartView,比方说 (15, 16, 17, 2, 3)
用这行代码
for i in 0..<gameStatsMonth.count {
let dataEntryTeam = ChartDataEntry(x: Double(gameStatsMonth[i].day!), y: Double(gameStatsMonth[i].points!))
lineDataEntryTeam.append(dataEntryTeam)
}
碰巧这些值显示在 xAxis 中排序,像这样:2, 3, 15, 16, 17。
有什么方法可以保持 x 值的第一顺序? (它们在 lineDataEntryTeam 中的插入顺序)
为 xAxis 添加一个数组(在您的函数之外):
var xaxisVals = [Double]()
更新您的 for
循环
for i in 0..<gameStatsMonth.count {
let dataEntryTeam = ChartDataEntry(x: Double(gameStatsMonth[i].day!), y: Double(gameStatsMonth[i].points!))
xaxisVals.append(Double(gameStatsMonth[i].day!))
lineDataEntryTeam.append(dataEntryTeam)
}
采用IAxisValueFormatter
:
class YourViewController: UIViewController, IAxisValueFormatter
填写委托方法:
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return xaxisVals[Int(value)]
}
在class中定义委托:
weak var axisFormatDelegate: IAxisValueFormatter?
在 viewDidLoad
中将委托设置为 self
:
axisFormatDelegate = self
for循环后,设置xAxis:
let xaxis = lineDataEntryTeam.xAxis
xaxis.granularityEnabled = true
xaxis.granularity = 1
xaxis.valueFormatter = axisFormatDelegate
我正在设置一个在 xAxis 上有一些值的 CombinedChartView,比方说 (15, 16, 17, 2, 3)
用这行代码
for i in 0..<gameStatsMonth.count {
let dataEntryTeam = ChartDataEntry(x: Double(gameStatsMonth[i].day!), y: Double(gameStatsMonth[i].points!))
lineDataEntryTeam.append(dataEntryTeam)
}
碰巧这些值显示在 xAxis 中排序,像这样:2, 3, 15, 16, 17。
有什么方法可以保持 x 值的第一顺序? (它们在 lineDataEntryTeam 中的插入顺序)
为 xAxis 添加一个数组(在您的函数之外):
var xaxisVals = [Double]()
更新您的 for
循环
for i in 0..<gameStatsMonth.count {
let dataEntryTeam = ChartDataEntry(x: Double(gameStatsMonth[i].day!), y: Double(gameStatsMonth[i].points!))
xaxisVals.append(Double(gameStatsMonth[i].day!))
lineDataEntryTeam.append(dataEntryTeam)
}
采用IAxisValueFormatter
:
class YourViewController: UIViewController, IAxisValueFormatter
填写委托方法:
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return xaxisVals[Int(value)]
}
在class中定义委托:
weak var axisFormatDelegate: IAxisValueFormatter?
在 viewDidLoad
中将委托设置为 self
:
axisFormatDelegate = self
for循环后,设置xAxis:
let xaxis = lineDataEntryTeam.xAxis
xaxis.granularityEnabled = true
xaxis.granularity = 1
xaxis.valueFormatter = axisFormatDelegate