【发布时间】:2020-04-02 07:18:52
【问题描述】:
如何在 x 轴上设置字符串 0 标签?我希望它显示“现在”而不是日期类型。
我已经看到了仅有助于格式化一个特定标签的功能,但我不知道它是如何工作的。此外,我还没有看到任何例子。那么,getFormattedLabel(index: Int) 是如何工作的呢?
这就是我需要我的 xAxis 的样子:
谢谢!
【问题讨论】:
标签: ios swift charts axis-labels ios-charts
如何在 x 轴上设置字符串 0 标签?我希望它显示“现在”而不是日期类型。
我已经看到了仅有助于格式化一个特定标签的功能,但我不知道它是如何工作的。此外,我还没有看到任何例子。那么,getFormattedLabel(index: Int) 是如何工作的呢?
这就是我需要我的 xAxis 的样子:
谢谢!
【问题讨论】:
标签: ios swift charts axis-labels ios-charts
您可以将您的xAxis.valueFormatter 设置为您自己的自定义类,然后当您的 x 值为 0 时立即返回。
喜欢:
class ChartValueFormatter: NSObject, IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
if value == 0 {
return "Now"
}
let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("dd MMM")
dateFormatter.locale = .current
let date = Date(timeIntervalSince1970: value)
return dateFormatter.string(from: date)
}
}
为此,您需要根据日期对值进行排序,然后将现在的值时间戳设置为零。
【讨论】:
花了一段时间才弄清楚,但我找到了a great tutorial on Medium by Spencer Mandrusiak
我需要创建 String 类型的第一个标签,而所有其他标签仍应为 Date 类型。 我做了什么:
这个解决方案对我很有效!
class ChartXAxisFormatter: NSObject, IAxisValueFormatter {
enum CustomLabel: Int {
case firstLabel
var label: String {
switch self {
case .firstLabel: return "Now"
}
}
}
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "hh:mm"
let date = Date(timeIntervalSince1970: value)
let time = dateFormatterPrint.string(from: date)
let intVal = Int(value)
let customLabel = CustomLabel(rawValue: intVal)
return customLabel?.label ?? "\(time)"
}
}
【讨论】:
这是一个 sn-p,它可以帮助我将 X 轴转换为时间轴,并在图表上制作字符串类型的最后一个标签。
使用index == count - 2是因为X轴上的标签计数被强制设置为3:
chart.xAxis.setLabelCount(3, force: true)
chart.xAxis.avoidFirstLastClippingEnabled = false
chart.xAxis.forceLabelsEnabled = true
class ChartXAxisFormatter: NSObject, IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
if let index = axis?.entries.firstIndex(of: value), let count = axis?.entries.count , index == count - 2 {
return "Now"
}
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm:ss"
let date = Date(timeIntervalSince1970: value)
let time = dateFormatterPrint.string(from: date)
return time
}
}
【讨论】: