I solved my own problem by using a YAxisRenderer
. I set up a custom YAxisRenderer
and changed the computeAxisValues
function to suit my own needs. Here is my code:
import Charts
class TimelineYAxisRender: YAxisRenderer{
/// Sets up the axis values. Computes the desired number of labels between the two given extremes.
@objc open override func computeAxisValues(min: Double, max: Double)
{
super.computeAxisValues(min: min, max: max)
guard let axis = self.axis else { return }
let labelCount = axis.labelCount
let range = max - min
// Ensure stops contains at least n elements.
axis.entries.removeAll(keepingCapacity: true)
axis.entries.reserveCapacity(labelCount)
let lowestHour = Int((min/60).rounded(.down))
let highestHour = Int((max/60).rounded(.up))
let rangeHour = highestHour - lowestHour
switch range {
case 160..<600:
for i in 0...2 * rangeHour{
axis.entries.append(Double(i) * 30 + Double(lowestHour * 60))
}
case 50..<160:
for i in 0...4 * rangeHour{
axis.entries.append(Double(i) * 15 + Double(lowestHour * 60))
}
case 15..<50:
for i in 0...12 * rangeHour{
axis.entries.append(Double(i) * 5 + Double(lowestHour * 60))
}
case 0..<15:
for i in 0...60 * rangeHour{
axis.entries.append(Double(i) + Double(lowestHour * 60))
}
default:
for i in 0...8{
axis.entries.append(Double(i) * 180)
}
}
}
}
My code to set the left y-axis to the new YAxisRenderer
:
let transformer = barChart.getTransformer(forAxis:.left)
let viewPortHandler = barChart.leftYAxisRenderer.viewPortHandler
barChart.leftYAxisRenderer = TimelineYAxisRender(viewPortHandler: viewPortHandler, yAxis: barChart.leftAxis, transformer: transformer)
I used a rounding system so I would only load the labels for the part of the graph the user can see, as loading every label would take up too much memory and cause the simulator to stutter. I also used the max - min to determine what labels to load to create a smooth zoom. When the new labels are loaded can be changed by changing the parameters for the switch cases, and the amount of zoom can be changed by changing what is actually appended to axis.entries
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.