iosswiftnscodermacaw

How to run a class again after is has been initialised


I have a graph which I want to load with data with recent results.

Here is a screenshot to show you what it looks like.

I am able to display the initial data correctly, however after that I cannot update the view to display the new data added to it.

The graph is a view on storyboard with custom class MacawChartView.

class ViewControllerResultsView: ViewController, GADInterstitialDelegate {

@IBOutlet var chartView: MacawChartView!    

override func viewDidLoad() {
    chartView.frame = CGRect(x: w/2 - (w * 0.95)/2, y: h * 0.57, width: w * 0.95, height: w * 0.45)
    chartView.backgroundColor = UIColor.init(displayP3Red: 253/255, green: 254/255, blue: 149/255, alpha: 1)
    chartView.contentMode = .scaleAspectFit
    MacawChartView.playAnimations()

I have tried a lot of different ways to 're-run' the graph so it rebuilds with updated data but cannot get passed the 'coder aDecoder: NSCoder' argument required. Here is the initialiser in MacawChartView.swift

    required init?(coder aDecoder: NSCoder){
    super.init(node: MacawChartView.createChart(), coder: aDecoder)
}

Thanks for any help. Please let me know if more information is needed etc.


Solution

  • The documentation isn't great for this library, but here's a solution for you. I started with the example project on gitHub, but I removed the init function and made the data var

    class CustomMacawView: MacawView {
    
    static var data: [Double] = [101, 142, 66, 178, 92]
    static let palette = [0xf08c00, 0xbf1a04, 0xffd505, 0x8fcc16, 0xd1aae3].map { val in Color(val: val)}
    
    
    public func updateData(newData : [Double])
    {
        CustomMacawView.data = newData
        updateDisplay()
    }
    
    public func updateDisplay()
    {
        let chart = CustomMacawView.createChart()
        self.node = Group(contents: [chart])
    }
    

    in my main view controller, I have a button to generate new data

    @IBAction func cmdUpdateGraph(_ sender: Any) {
        macawView.updateData(newData: [Double.random(in: 1...100),
                                       Double.random(in: 1...100),
                                       Double.random(in: 1...100),
                                       Double.random(in: 1...100),
                                       Double.random(in: 1...100)]) }