First you have to make sure you have a bridging header so you can access the objective C code, see this website:
How to call Objective-C code from Swift
Then, in the view controller you wish to generate the pie chart, you have to make sure you include the necessary methods to conform to the XYPieChartDataSource (at the bare minimum, the XYPieChartDelegate has additional optional methods), which are shown in swift here:
func pieChart(pieChart: XYPieChart!, valueForSliceAtIndex index: UInt) -> CGFloat {
return CGFloat(self.slices[Int(index)] as NSNumber)
}
func numberOfSlicesInPieChart(pieChart: XYPieChart!) -> UInt {
return UInt(self.slices.count)
}
func pieChart(pieChart: XYPieChart!, colorForSliceAtIndex index: UInt) -> UIColor! {
return self.sliceColors[Int(index)] as UIColor
}
And modify the ViewController header accordingly:
class YourViewController: UIViewController, XYPieChartDelegate, XYPieChartDataSource {
A good idea to add these instance variables above your viewDidLoad too:
// Pie Chart Properties
var slices:NSMutableArray = NSMutableArray(capacity: 10)
var sliceColors:NSArray!
var myPieChart:XYPieChart!
var indexOfSlices:UInt!
var numSlices:UInt = 0
var valueAtSlice:Int = 0
After that, you have set the values you want for your pie chart, I have this in an initializePieChart() method:
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: UIScreen.mainScreen().applicationFrame.size)
let midPointx = UIScreen.mainScreen().applicationFrame.width/2
var midPointy:CGFloat = 0
var rad:CGFloat = 0
let point = CGPoint(x: midPointx, y: midPointy)
You then , and can initialize the pieChart as so:
let aPieChart:XYPieChart = XYPieChart(frame: rect, center: point, radius: rad)
self.myPieChart = aPieChart
Then finally, set the dataSource you modify the properties of the piechart as so:
myPieChart.dataSource = self
myPieChart.delegate = self
//Various settings
myPieChart.setPieBackgroundColor(UIColor(red: 0.251, green: 0.251, blue: 0.251, alpha: 1.0))
myPieChart.startPieAngle = CGFloat(M_PI_2)
myPieChart.animationSpeed = 2.0
// Various settings
myPieChart.showPercentage = true
myPieChart.pieCenter = CGPointMake(midPointx, midPointy)
myPieChart.userInteractionEnabled = false
myPieChart.labelShadowColor = UIColor.blackColor()
//For getting data into the slices
self.sliceColors = [UIColor(red: 104/255, green: 1, blue: 67/255, alpha: 1),
UIColor(red: 23/255, green: 247/255, blue: 252/255, alpha: 1),
UIColor(red: 1, green: 0.231, blue: 0.188, alpha: 1)]
for i in 0...2 {
//This is just initializing the slices, you'll have to insert the data elsewhere using self.slices.replaceObjectAtIndex(0, withObject: dataVariable)
var one:NSNumber = 0
self.slices.addObject(one)
}
Then finally, DONT FORGET TO RELOAD THE DATA and add to the subview
self.pieChartView.setTranslatesAutoresizingMaskIntoConstraints(false)
myPieChart.reloadData()
self.pieChartView.addSubview(myPieChart)
That should do it!