快速堆积的条形图

时间:2017-07-11 12:07:40

标签: swift ios-charts

我使用Swift中的Charts library绘制条形图。

这是我的代码:

class barChartVC: UIViewController {

    let months = ["January" , "February" , "March" , "April" , "May" , "June" , "July" , "August"]
    let unitsSold = [10.0,20.0,30.0,20.0,20.0,10.0,15.0,20.0]
    let unitsSold1 = [20.0,30.0,50.0,40.0,30.0,20.0,45.0,50.0]

    var dataEntries: [BarChartDataEntry] = []
    @IBOutlet var barChartView: BarChartView!

    override func viewDidLoad() {
        super.viewDidLoad()

        setChartBarGroupDataSet(dataPoints: months, values: unitsSold, values2: unitsSold1, sortIndex: 0)
    }

    func setChartBarGroupDataSet(dataPoints: [String], values: [Double], values2: [Double],sortIndex:Int) {
        for i in 0..<dataPoints.count
        {
            let dataEntry = BarChartDataEntry(x: values[i], y: Double(i))
            let dataEntry1 = BarChartDataEntry(x: values2[i], y: Double(i))
            dataEntries.append(dataEntry)
            dataEntries.append(dataEntry1)
        }

        let chartDataSet = BarChartDataSet(values: dataEntries, label: " ")

        var COLOR_SET = [UIColor]()
        COLOR_SET = [UIColor.red,UIColor.green]

        chartDataSet.setColors(COLOR_SET, alpha: 1.0)

        let dataSets: [BarChartDataSet] = [chartDataSet]

        let data = BarChartData(dataSets: dataSets)
        barChartView.data = data // Fatal error is here

        barChartView.descriptionText = "Bar Chart"
        barChartView.rightAxis.drawGridLinesEnabled = false
        barChartView.rightAxis.drawAxisLineEnabled = false
        barChartView.rightAxis.drawLabelsEnabled = false
        barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .easeInBounce)   
    }
}

我在代码中标记的行上收到致命错误。

  

致命错误:在解包可选值时意外发现nil

提前感谢帮助我的人。

1 个答案:

答案 0 :(得分:1)

我能够毫无错误地运行您的代码。我相信你面临的问题是IBOutlet。

确保故事板中的选定类是BarChartView和 您在Storyboard中的视图已连接到ViewController中的IBOutlet

enter image description here