如何使用 ios 'Charts' cocoapod 解决 CoreGraphics 中的 NaN 错误?

How do I resolve NaN error in CoreGraphics with ios 'Charts' cocoapod?

我 运行 我的图表时出现以下错误。我该如何解决这个问题?

我目前正在使用 Daniel Gindi cocoapod 'Charts'。

发生此错误时,数据不会绘制在图表上。

“错误:此应用程序或其使用的库已将无效数值(NaN 或非数字)传递给 CoreGraphics API,此值被忽略。请修复此问题问题。"

您遇到的错误非常简单。您正在向核心图形提供 NaN 值。这是一种特殊值,通常由未定义的结果产生,例如除以零。 (其他一些类似的情况表明误用三角函数时常见的无穷大或负无穷大)。

在绘制图表的情况下,您可以考虑这个非常简单的例子,它已经足够了:

override func viewDidLoad() {
    super.viewDidLoad()
    
    class ChartView: UIView {
        var values: [CGFloat] = []
        
        override func draw(_ rect: CGRect) {
            super.draw(rect)
            
            guard values.isEmpty == false else { return }
            
            let dx: CGFloat = bounds.width/CGFloat(values.count)
            let maxValue = values.max()!
            
            var x = dx*0.5 // Start position
            let path = UIBezierPath()
            var isFirstValue: Bool = true
            
            values.forEach { value in
                defer { x += dx }
                guard !isFirstValue else {
                    path.move(to: .init(x: x, y: (1.0 - value/maxValue)*bounds.height))
                    isFirstValue = false
                    return
                }
                path.addLine(to: .init(x: x, y: (1.0 - value/maxValue)*bounds.height))
            }
            
            path.stroke()
        }
    }
    
    let chartView = ChartView(frame: .init(x: 10.0, y: 100.0, width: 300.0, height: 200.0))
    chartView.backgroundColor = .gray
    chartView.values = [1, 2, 4, 4, 3, 1, 3, 12]
    view.addSubview(chartView)
}

您可以创建一个新项目并简单地修改您自动生成的 viewDidLoad 来尝试。

只要我做了一些愚蠢的事情,比如chartView.values = [0, 0],错误就会被打印出来,比如

Error: this application, or a library it uses, has passed an invalid numeric value (NaN, or not-a-number) to CoreGraphics API and this value is being ignored. Please fix this problem.

我不确定“图表”cocoapod 的作用,但就我而言,我会说该错误出在绘制图表的工具中。但是,您应该能够检查您尝试绘制的数据是否真的有意义。