swift:重新加载视图以在图表中显示新数据

时间:2016-08-30 12:28:28

标签: ios swift view charts reload

即时通讯使用图表框架“图表”,但是对于包含新数据的图表,它没有重新加载功能。它只能在加载viewController时显示一次图表。但我想用表中的选择重新加载视图/图表。 (该表位于其他viewcontroller中)

在我的情况下,我有一个ViewController,里面有一个视图 和数据分为两个数组:x和y

func setChartData(x: [Double], y: [Double])

我试图调用该函数但它没有显示它。 如果从viewWillAppear()调用该函数 图表仅显示,如果我切换到另一个视图控制器并切换回

我该如何解决这个问题

self.view!函数内的.setNeedsDisplay()无效。

我的viewcontroller:

override func viewWillAppear(animated: Bool) {
    setChartData(resultID_statistics, y: resultWeight_statistics)

}

func setChartData(x: [Double], y: [Double])  {

    // 1 - creating an array of data entries
    var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < x.count; i++ {
        yVals1.append(ChartDataEntry(value: y[i], xIndex: i))
    }

    // 2 - create a data set with our array
    let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: "First Set")
    set1.axisDependency = .Left // Line will correlate with left axis values
    set1.setColor(UIColor.redColor().colorWithAlphaComponent(0.5)) // our line's opacity is 50%
    set1.setCircleColor(UIColor.redColor()) // our circle will be dark red
    set1.lineWidth = 2.0
    set1.circleRadius = 6.0 // the radius of the node circle
    set1.fillAlpha = 65 / 255.0
    set1.fillColor = UIColor.redColor()
    set1.highlightColor = UIColor.whiteColor()
    set1.drawCircleHoleEnabled = true

    //3 - create an array to store our LineChartDataSets
    var dataSets : [LineChartDataSet] = [LineChartDataSet]()
    dataSets.append(set1)

    //4 - pass our months in for our x-axis label value along with our dataSets
    let data: LineChartData = LineChartData(xVals: x, dataSets: dataSets)
    data.setValueTextColor(UIColor.whiteColor())

    //5 - finally set our data
    self.lineChartView.data = data

    data.notifyDataChanged()
    lineChartView.notifyDataSetChanged()

}

1 个答案:

答案 0 :(得分:6)

从他们的文档中看来,您需要通知数据集的更改:

 // EXAMPLE 1
 // add entries to the "data" object
 exampleData.addEntry(...);
 chart.notifyDataSetChanged(); // let the chart know it's data changed
 chart.invalidate(); // refresh

 // EXAMPLE 2
 // add entries to "dataSet" object
 dataSet.addEntry(...);
 exampleData.notifyDataChanged(); // let the data know a dataSet changed
 chart.notifyDataSetChanged(); // let the chart know it's data changed
 chart.invalidate(); // refresh

有关详细信息,请查看他们的wiki

注意:来自repo README:

  

目前还不需要iOS / tvOS / OSX的文档   版本,因为API与Android上的95%相同。您可以在此处阅读官方MPAndroidChart文档:Wiki

所以当你点击链接并看到&#34; MPAndroidChart&#34;不要惊慌:)

您也可以尝试:

chart.data.notifyDataChanged()
chart.notifyDataSetChanged()

这取自他们在objective-c中的示例项目:

  LineChartDataSet *set1 = nil;
    if (_chartView.data.dataSetCount > 0)
    {
        set1 = (LineChartDataSet *)_chartView.data.dataSets[0];
        set1.values = values;
        [_chartView.data notifyDataChanged];
        [_chartView notifyDataSetChanged];
    }