I am trying to render a basic bar chart with this code:
import UIKit
import CorePlot
class BarChart: CPTGraphHostingView, CPTPlotDataSource, CPTPlotDelegate, CPTPlotSpaceDelegate
{
let data: [[UInt]] = [
[30, 40, 100],
[10, 44, 35]
]
func renderData() {
let barGraph = CPTXYGraph(frame: self.bounds)
self.hostedGraph = barGraph
barGraph.axisSet = nil
var space: CPTXYPlotSpace = barGraph.defaultPlotSpace as! CPTXYPlotSpace
barGraph.addPlotSpace(space)
space.yRange = CPTPlotRange(locationDecimal: CPTDecimalFromFloat(0), lengthDecimal: CPTDecimalFromFloat(50))
space.xRange = CPTPlotRange(locationDecimal: CPTDecimalFromFloat(0), lengthDecimal: CPTDecimalFromFloat(3))
space.delegate = self
var bar = CPTBarPlot(frame: barGraph.bounds)
bar.dataSource = self
bar.barWidth = 3
barGraph.addPlot(bar, toPlotSpace: space)
}
func numberForPlot(plot: CPTPlot, field: UInt, recordIndex: UInt ) -> AnyObject? {
return data[0][Int(idx)]
}
func barFillForBarPlot(barPlot: CPTBarPlot, recordIndexRange indexRange: NSRange) -> AnyObject? {
return CPTFill(color: CPTColor(componentRed: 0, green: 0, blue: 255, alpha: 1))
}
func numberOfRecordsForPlot(plot: CPTPlot) -> UInt {
return 3
}
}
This class is associated with a view in storyboard. Unfortunately, I can't manage to display any data (but axis are visible when i remove the line with barGraph.axisSet = nil
). Am I missing something? Thanks!
When using Swift, I would recommend getting the version of Core Plot on the "release-2.0" branch from GitHub. It has some API changes to make working with Swift easier. The biggest one is offering alternatives to the methods and properties that use NSDecimal
values, eg, plot ranges. I hope to have release 2.0 done soon after Xcode 7 is final.
There's no need to add the default plot space to the graph; it's already there.
The -numberForPlot:field:recordIndex:
function should return the value as an NSNumber
. Cast the value when returning it, eg, return data[0][Int(idx)] as NSNumber
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.