2017-07-11 242 views
0

我在Swift中使用Charts library繪製條形圖。swift堆積條形圖

這裏是我的代碼:

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) 
    } 
} 

我越來越對我標誌着代碼行一個致命的錯誤。

fatal error: unexpectedly found nil while unwrapping an Optional value

非常感謝您幫助我的人。

+1

「獲得了標誌着我在代碼行致命錯誤」而什麼錯誤到底?什麼是整個錯誤信息?通常,它是詳細而且有用的調試。 – Larme

+0

嘗試更改:'let data = BarChartData(dataSets:dataSets)'爲'let data = BarChartData(dataSet:dataSets)' –

+0

@NoahCristino嘗試了您的建議,仍然是同樣的致命錯誤。 – swiftuser123

回答

1

我能夠毫無錯誤地運行你的代碼。我相信你面臨的問題是IBOutlet。

確保在您的故事板選定類是BarChartView和 ,你在故事板視圖連接到IBOutlet中在你的ViewController

enter image description here