Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a pie chart in swift

I'm trying to create a pie chart in swift, and would like to create the code from scratch rather than use a 3rd party extension.

I like the idea of it being @IBDesignable, so I started with this:

import Foundation
import UIKit

@IBDesignable class PieChart: UIView {

  var data:  Dictionary<String,Int>?

  required init(coder aDecoder: NSCoder) {
    super.init(coder:aDecoder)!
    self.contentMode = .Redraw
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.clearColor()
    self.contentMode = .Redraw
  }

  override fun drawRect(rect: CGRect) {
    // draw the chart in here
  }

}

What I'm not sure about, is how best to get the data into the chart. Should I have something like this:

@IBOutlet weak var pieChart: PieChart!
override func viewDidLoad() {
    pieChart.data = pieData
    pieChart.setNeedsDisplay()
}

Or is there a better way? Presumably, there is no way to include the data in the init function?

Thanks in advance!

like image 627
Ben Avatar asked Nov 26 '15 17:11

Ben


People also ask

How do you create a chart in Swift?

To create a chart with Swift Charts, define your data and initialize a Chart view with marks and data properties. Then use modifiers to customize different components of the chart, like the legend, axes, and scale.


1 Answers

You could create a convenience init that includes the data, but that would only be useful if you are creating the view from code. If your view is added in the Storyboard, you will want a way to set the data after the view has been created.

It is good to look at the standard UI elements (like UIButton) for design clues. You can change properties on a UIButton and it updates without you having to call myButton.setNeedsDisplay(), so you should design your pie chart to work in the same manner.

It is fine to have a property of your view that holds the data. The view should take responsibility for redrawing itself, so define didSet for your data property and call setNeedsDisplay() there.

var data:  Dictionary<String,Int>? {
    didSet {
        // Data changed.  Redraw the view.
        self.setNeedsDisplay()
    }
}

Then you can simply set the data, and the pie chart will redraw:

pieChart.data = pieData

You can extend this to other properties on your pie chart. For instance, you might want to change the background color. You'd define didSet for that property as well and call setNeedsDisplay.

Note that setNeedsDisplay just sets a flag and the view will be drawn later. Multiple calls to setNeedsDisplay won't cause your view to redraw multiple times, so you can do something like:

pieChart.data = pieData
pieChart.backgroundColor = .redColor()
pieChart.draw3D = true  // draw the pie chart in 3D

and the pieChart would redraw just once.

like image 129
vacawama Avatar answered Sep 30 '22 11:09

vacawama