我正在使用iOS图表(V3.3)绘制水平条形图,以获取体育应用程序的球员表现统计信息。我希望条形值分别显示在条形旁。我可以做到这一点,只要玩家同时拥有正面和负面的表现点,但是如果玩家只有正面的表现点,则不会显示任何值。
我在自己的类中有BarChartView,并且正在使用此代码
import Charts
class PlayerPerformanceBarChart: HorizontalBarChartView, IValueFormatter {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setChart(pf: [PerformanceStat]) {
noDataTextColor = Style.labelText
noDataText = gf.getLiteral("noPerformanceData")
isUserInteractionEnabled = false
legend.enabled = false
leftAxis.enabled = false
rightAxis.enabled = false
chartDescription?.text = nil
drawValueAboveBarEnabled = true
// Data
var dataEntries: [BarChartDataEntry] = []
var labels: [String] = []
for i in 0..<pf.count {
dataEntries.append(BarChartDataEntry(x: Double(i), y: Double(pf[i].playerPoints)))
labels.append(pf[i].playerAction)
}
let chartDataSet = BarChartDataSet(entries: dataEntries, label: nil)
chartDataSet.colors = ChartColorTemplates.joyful()
chartDataSet.valueFormatter = self
let chartData = BarChartData(dataSets: [chartDataSet])
chartData.setDrawValues(true)
// X Axis - which for a Horizontal Bar Chart is actually the vertical (Y) axis - I know, crazy but true!!
let xaxis = self.xAxis
xaxis.drawGridLinesEnabled = false
xaxis.labelPosition = .bottom
xaxis.labelCount = pf.count
xaxis.axisMinimum = -1
xaxis.resetCustomAxisMin()
xaxis.centerAxisLabelsEnabled = false
xaxis.granularity = 1
xaxis.granularityEnabled = true
xaxis.labelTextColor = Style.chartText
xaxis.valueFormatter = IndexAxisValueFormatter(values: labels)
clipValuesToContentEnabled = true
//Chart Format and Display
data = chartData
}
func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
return Int(value).description
}
}
setChart函数由包含的视图(即UIScrollView)调用
它只是一个数据集,因此没有分组。我无法找出为什么在没有负值要显示的情况下无法显示这些值。看一下Charts代码,这与条形图的位置在视口处理程序的边界之外有关,但是我看不出为什么会这样。
任何帮助将不胜感激
答案 0 :(得分:0)
最好创建一个单独的类负责值的格式。
import UIKit
import Charts
class ValueFormatter: NSObject, IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
/// your code for formatting the values
}
}
并且您应该将自定义类分配为值格式器:
xAxis.valueFormatter = ValueFormatter()
除此之外,请看一下关于如何设置标签的自定义值的精彩教程:https://medium.com/@spmandrus/ios-charts-custom-y-axis-values-e03cac8850c