gpt4 book ai didi

iOS 图表未显示所有 xAxis 值

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:39 24 4
gpt4 key购买 nike

我正在用 Swift 4.2 编写一个 iOS 应用我正在使用 Charts库显示水平条形图。我需要设置它的 xAxis 值。仅显示最后一个值。

问题截图: enter image description here

代码片段:

@IBOutlet var chartView: HorizontalBarChartView!

override func viewDidLoad() {
super.viewDidLoad()

let xAxis = chartView.xAxis
xAxis.labelPosition = .bottom
xAxis.labelFont = .systemFont(ofSize: 10)
xAxis.drawAxisLineEnabled = false
xAxis.drawGridLinesEnabled = false
xAxis.granularity = 1
xAxis.enabled=true

xAxis.setLabelCount(3, force: false) //Not working as per expectations
xAxis.valueFormatter=IndexAxisValueFormatter(values: ["A","B","C"]) //Not working as per expectations




self.setDataCount(3,values:[142000,122400,100110])
chartView.animate(yAxisDuration: 2.5)
}


func setDataCount(_ count: Int, values:[Double]) {
let barWidth = 2.0
let spaceForBar = 4.0
var n=0
let yVals = (0..<count).map { (i) -> BarChartDataEntry in

let val = values[n]
n+=1

return BarChartDataEntry(x: Double(i)*spaceForBar, y: val)

}

let set1 = BarChartDataSet(entries: yVals, label: "DataSet")
set1.drawIconsEnabled = false

let data = BarChartData(dataSet: set1)
data.setValueFont(UIFont(name:"HelveticaNeue-Light", size:10)!)
data.barWidth = barWidth

chartView.data = data

//let xAxis = chartView.xAxis
//xAxis.setLabelCount(3, force: false)
//xAxis.valueFormatter=IndexAxisValueFormatter(values: ["A","B","C"])
}

我试图找到解决方案:

xAxis.valueFormatter=IndexAxisValueFormatter(values: ["A","B","C"]) 

但是这些都不起作用。

最佳答案

发生这种情况是因为 IndexAxisValueFormatter 的默认功能

你必须像这样编写你自己的自定义 IAxisValueFormatter

final class CustomFormatter: IAxisValueFormatter {

var labels: [String] = []

func stringForValue(_ value: Double, axis: AxisBase?) -> String {

let count = self.labels.count

guard let axis = axis, count > 0 else {
return ""
}

let factor = axis.axisMaximum / Double(count)

let index = Int((value / factor).rounded())

if index >= 0 && index < count {
return self.labels[index]
}

return ""
}
}

然后像这样使用它

 let customFormater = CustomFormater()
customFormater.labels = ["A","B","C"]

chartView.xAxis.valueFormatter = customFormater

确保数据和标签的大小/数量相同,否则不会给您想要的结果。

关于iOS 图表未显示所有 xAxis 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55693095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com