I try to update the chart's data programmatically, however I fail to do so.
Initially, I build the chart showing one price fetched from UserDefaults using the function buildChart()
.
From time to time, I want to update the chart's data using the function updateChartData()
. I tried appending elements to chartsData
, however, this fails with the error
Cannot use mutating member on immutable value: 'chartsData' is a get-only property
Can anyone assist? My rough code so far is:
import UIKit
import FLCharts
class AnalysisViewController: UIViewController {
@IBOutlet weak var chartView: FLChart!
override func viewDidLoad() {
super.viewDidLoad()
// Listen to silent notification to reload graph when new stock price was fetched and received by this view
NotificationCenter.default.setObserver(self, selector: #selector(updateChartData), name: NSNotification.Name(rawValue: "stockPriceFetchedForGraphUpdate"), object: nil)
buildChart()
}
@objc func updateChartData() {
print("update")
}
func buildChart() {
let priceNow = UserDefaults.standard.double(forKey: "stockPriceLastFetchedAmount")
var chartsData: [MultiPlotable] {
[MultiPlotable(name: "", values: [priceNow]),]
}
let barChartData = FLChartData(title: "",
data: chartsData,
legendKeys: [
Key(key: "", color: FLColor(UIColor(named: "Gold") ?? .label))
],
unitOfMeasure: "Euro")
barChartData.xAxisUnitOfMeasure = ""
barChartData.yAxisFormatter = .decimal(2)
//let lineChart = FLChart(data: barChartData, type: .line(config: FLLineConfig(width: 3, capStyle: .square, backgroundFill: FLColor(UIColor(named: "Gold")?.withAlphaComponent(0.2) ?? .clear), isSmooth: true)))
let priceChart = FLChart(data: barChartData, type: .line(config: FLLineConfig(width: 3, capStyle: .butt, backgroundFill: FLColor(UIColor(named: "Gold")?.withAlphaComponent(0.2) ?? .label), showCircles: false, isSmooth: true, circleColor: UIColor(named: "Gold") ?? .label)))
priceChart.config = FLChartConfig(granularityY: (priceNow / 5).rounded()) // to nearest 500
priceChart.shouldScroll = false
priceChart.showAverageLine = true
priceChart.showTicks = false
chartView.addSubview(priceChart)
priceChart.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
priceChart.centerYAnchor.constraint(equalTo: self.chartView.centerYAnchor),
priceChart.centerXAnchor.constraint(equalTo: self.chartView.centerXAnchor),
priceChart.heightAnchor.constraint(equalToConstant: self.chartView.frame.height * 1),
priceChart.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width * 0.9),
])
}
}