iOS CorePlot point conversion - ios

I am experimenting with Core Plot. I am trying to add a custom "goal" label over the graph at x: 2.0, y: 50.0 - basically label over the y == 50, its in a separate view, which means I need to convert my point from Core Plot to my UIView bounds. I have not found a combination of points conversions from layer/views that works across all iPhones screen sizes. In my pictures below iPhone 6s is the closest.
iPhone 6s+:
iPhone 6s:
iPhone 5s:
My view layout:
Here is my class:
class BarChartViewController: UIViewController, CPTBarPlotDataSource
{
private var barGraph : CPTXYGraph? = nil
#IBOutlet weak var textBox: UILabel!
#IBOutlet weak var graphHostingView: CPTGraphHostingView!
#IBOutlet weak var textBoxView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(false, animated: false)
self.title = "My results"
let newGraph = CPTXYGraph(frame: CGRectZero)
let theme = CPTTheme(named: kCPTPlainWhiteTheme)
newGraph.applyTheme(theme)
let hostingView = graphHostingView
hostingView.hostedGraph = newGraph
if let frameLayer = newGraph.plotAreaFrame
{
// Border
frameLayer.borderLineStyle = nil
frameLayer.cornerRadius = 0.0
frameLayer.masksToBorder = false
// Paddings
newGraph.paddingLeft = 0.0
newGraph.paddingRight = 0.0
newGraph.paddingTop = 0.0
newGraph.paddingBottom = 0.0
frameLayer.paddingLeft = 70.0
frameLayer.paddingTop = 20.0
frameLayer.paddingRight = 20.0
frameLayer.paddingBottom = 80.0
}
// Plot space
let plotSpace = newGraph.defaultPlotSpace as? CPTXYPlotSpace
plotSpace?.yRange = CPTPlotRange(location: 0.0, length: 100.0)
plotSpace?.xRange = CPTPlotRange(location: 0.0, length: 4.0)
let axisSet = newGraph.axisSet as? CPTXYAxisSet
if let x = axisSet?.xAxis {
x.axisLineStyle = nil
x.majorTickLineStyle = nil
x.minorTickLineStyle = nil
x.majorIntervalLength = 5.0
x.orthogonalPosition = 0.0
x.title = "X Axis"
x.titleLocation = 7.5
x.titleOffset = 55.0
// Custom labels
x.labelRotation = CGFloat(M_PI_4)
x.labelingPolicy = .None
let customTickLocations = [0.5, 1.5, 2.5]
let xAxisLabels = ["Label A", "Label B", "Label C"]
var labelLocation = 0
var customLabels = Set<CPTAxisLabel>()
for tickLocation in customTickLocations
{
let newLabel = CPTAxisLabel(text: xAxisLabels[labelLocation], textStyle: x.labelTextStyle)
labelLocation += 1
newLabel.tickLocation = tickLocation
newLabel.offset = x.labelOffset + x.majorTickLength
newLabel.rotation = 0 //CGFloat(M_PI_4)
customLabels.insert(newLabel)
}
x.axisLabels = customLabels
}
if let y = axisSet?.yAxis
{
y.axisLineStyle = nil
y.majorGridLineStyle = CPTMutableLineStyle()
var style = y.majorTickLineStyle?.mutableCopy() as? CPTMutableLineStyle
//style!.lineColor = CPTColor(CGColor: UIColor.blackColor()) //UIColor.blackColor())
style!.lineWidth = 10.0
y.minorGridLineStyle = CPTMutableLineStyle()
style = y.minorTickLineStyle?.mutableCopy() as? CPTMutableLineStyle
//style.lineColor = UIColor.redColor()
style!.lineWidth = 10.0
style!.lineCap = .Round
y.majorTickLength = 10.0
y.majorIntervalLength = 50.0
y.orthogonalPosition = 0.0
y.title = "Y Axis"
y.titleOffset = 45.0
y.titleLocation = 150.0
y.labelRotation = 0
y.labelingPolicy = .None
let customTickLocations = [50, 100]
let yAxisLabels = ["50", "100"]
var labelLocation = 0
var customLabels = Set<CPTAxisLabel>()
for tickLocation in customTickLocations
{
let newLabel = CPTAxisLabel(text: yAxisLabels[labelLocation], textStyle: y.labelTextStyle)
labelLocation += 1
newLabel.tickLocation = tickLocation
newLabel.offset = y.labelOffset + y.majorTickLength
newLabel.rotation = 0 //CGFloat(M_PI_4)
customLabels.insert(newLabel)
}
y.axisLabels = customLabels
var nums = Set<NSNumber>()
nums.insert(NSNumber(double: 50.0))
y.majorTickLocations = nums
}
// First bar plot
let barPlot1 = CPTBarPlot.tubularBarPlotWithColor(CPTColor.yellowColor(), horizontalBars: false)
barPlot1.baseValue = 0.0
barPlot1.dataSource = self
//barPlot1.barOffset = 0.5
barPlot1.identifier = "Bar Plot 1"
let textStyle = CPTMutableTextStyle()
textStyle.color = CPTColor.redColor()
textStyle.fontSize = 10.0
barPlot1.labelTextStyle = textStyle
newGraph.addPlot(barPlot1, toPlotSpace: plotSpace)
self.barGraph = newGraph
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.view.layoutIfNeeded()
let point: [Double] = [2.0, 50.0]
let plotPoint = UnsafeMutablePointer<Double>(point)
var dataPoint = self.barGraph?.defaultPlotSpace?.plotAreaViewPointForDoublePrecisionPlotPoint(plotPoint, numberOfCoordinates: 2)
//dataPoint = graphHostingView.layer.convertPoint(dataPoint!, fromLayer: self.barGraph!.plotAreaFrame!.plotArea)
dataPoint = graphHostingView.layer.convertPoint(dataPoint!, toLayer: graphHostingView.layer.superlayer)
//dataPoint = barGraph?.convertPoint(dataPoint!, fromLayer: graphHostingView.layer)
dataPoint = self.textBoxView.convertPoint(dataPoint!, fromView: graphHostingView)
print(dataPoint!)
for item in (self.textBoxView?.constraints)!
{
if let id = item.identifier
{
if id == "goalX"
{
print(item.constant)
item.constant = CGFloat((dataPoint?.x)!) - item.constant
}
else if id == "goalY"
{
print(item.constant)
item.constant = CGFloat((dataPoint?.y)!) - item.constant
}
}
}
barGraph?.titleDisplacement = CGPoint(x: dataPoint!.x * -1, y: dataPoint!.y * -1)
barGraph?.titlePlotAreaFrameAnchor = .TopLeft
self.textBoxView?.layoutIfNeeded()
}
}
Based on some other questions I have seen about CorePlot I know I need to convert it from CorePlot layer to my new view. I left some of my experiments in viewWillAppear() to see what I have tried. None of the solutions on SO seemed to work and I am new to iOS so probably missing something. Any ideas of what conversions I need to do to get my label to show up properly across all screen sizes?

You're on the right track with the point conversion. This is how I would do it:
// Update layer layout if needed
self.view.layoutIfNeeded()
graphHostingView.layer.layoutIfNeeded()
// Point in data coordinates
let point: [Double] = [2.0, 50.0]
// Data point in plot area layer coordinates
var dataPoint = self.barGraph?.defaultPlotSpace?.plotAreaViewPointForPlotPoint(point)
// Convert data point to graph hosting view coordinates
dataPoint = graphHostingView.layer.convertPoint(dataPoint!, fromLayer: self.barGraph!.plotAreaFrame!.plotArea)
Use this to update the constraints on the text box relative to the graph hosting view.

Related

iOS Swift Chart : Bar chart background colour

I create a bar chart that works completely fine. How can I add the bar chart capsule background color? Not want the entire chart background color but I want to need a background color for each bar so it will look like fill and unfill like effet to the bar chat.
var BAR_WIDTH_CONSTANT: CGFloat = 3
var BAR_DISTANCE: CGFloat = 14
var BAR_MAX_HEIGHT: CGFloat = 50
let MAX_VALUE: CGFloat = 60
let MIN_VALUE: CGFloat = 0
var unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0]
var months = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
var graphType = 1
var maxValue = 30.0
func setChart(arrX:[String]) {
let customFormater = BarChartFormatter()
customFormater.months = self.months
viewChart.xAxis.valueFormatter = customFormater
self.viewChart.xAxis.labelPosition = XAxis.LabelPosition.bottom
self.viewChart.setVisibleXRangeMaximum(Double(arrX.count))
self.viewChart.fitScreen()
var dataEntries = [BarChartDataEntry]()
for i in 0..<months.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: Double(unitsSold[i]), data: months as AnyObject?)
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(entries: dataEntries, label: "")
chartDataSet.valueTextColor = .clear
chartDataSet.valueFont = themeFont(size: 9, fontname: .Poppins_Black)
chartDataSet.colors = [.appThemeColor, UIColor(named: "DarkGreen")!]
//Remove 0 value from graphs
let noZeroFormatter = NumberFormatter()
noZeroFormatter.zeroSymbol = ""
chartDataSet.valueFormatter = DefaultValueFormatter(formatter: noZeroFormatter)
chartDataSet.barShadowColor = .clear
let chartData = BarChartData(dataSet: chartDataSet)
chartData.barWidth = 0.6
// if graphType == 1 || graphType == 3 {
// chartData.barWidth = 0.4
// }
viewChart.data = chartData
viewChart.animate(xAxisDuration: 1, yAxisDuration: 1, easingOption: .linear)
}
func setupChart() {
viewChart.delegate = self
viewChart.chartDescription.enabled = false
viewChart.dragEnabled = true
viewChart.doubleTapToZoomEnabled = false
viewChart.pinchZoomEnabled = false
viewChart.xAxis.valueFormatter = self
viewChart.legend.enabled = false
viewChart.setScaleEnabled(false)
viewChart.isUserInteractionEnabled = false
let leftAxisFormatter = NumberFormatter()
leftAxisFormatter.maximumFractionDigits = 0
let xAxis = viewChart.xAxis
xAxis.drawGridLinesEnabled = true
xAxis.labelPosition = .topInside
xAxis.labelRotationAngle = 0
xAxis.labelFont = themeFont(size: 12, fontname: .Poppins_Light)
xAxis.labelTextColor = .darkGray
xAxis.granularity = 1
xAxis.axisLineWidth = 0
xAxis.labelCount = 12
xAxis.granularityEnabled = true
xAxis.valueFormatter = self
xAxis.labelRotationAngle = 0
xAxis.gridColor = .clear
let yAxis = viewChart.leftAxis
yAxis.drawGridLinesEnabled = false
yAxis.axisMinimum = 0
yAxis.axisMaximum = Double(maxValue)
yAxis.axisLineWidth = 0
yAxis.labelTextColor = .clear
yAxis.drawLabelsEnabled = true
yAxis.labelPosition = .outsideChart
let dAxis = viewChart.rightAxis
dAxis.drawGridLinesEnabled = false
dAxis.axisMinimum = 0
dAxis.axisLineWidth = 0
dAxis.labelTextColor = .clear
dAxis.drawLabelsEnabled = true
dAxis.labelPosition = .outsideChart
}
This is what I'm looking for.
This is what I have done yet.
if you are drwaing your BarChart using Charts, then to apply corner radius you should have to change the internal code of the Charts Framework.
You can do it as:
Search (Shift+Command+O) for the BarChartRenderer.swift (Shift+Command+O) file and replace the (every)line
context.fill(barRect)
with the code below
let bezierPath = UIBezierPath(roundedRect: barRect, cornerRadius: 3.0)
context.addPath(bezierPath.cgPath)
context.drawPath(using: .fill)

Only one label appearing on a BarChart created with Charts

I want to create a BarChart with the Charts library. Everything is working good except the labels on the x axis. Only the first label "Jan" is appearing on the line. This is my code
override func viewWillAppear(_ animated: Bool) {
doBarChart()
}
func doBarChart(){
barChartView.drawBarShadowEnabled = false
barChartView.drawValueAboveBarEnabled = true
barChartView.chartDescription?.enabled = false
barChartView.maxVisibleCount = 60
let xAxis = barChartView.xAxis
xAxis.axisLineColor = UIColor.black
xAxis.labelPosition = .bottom
xAxis.drawAxisLineEnabled = true
xAxis.drawGridLinesEnabled = false
xAxis.granularity = 1.0
xAxis.labelCount = 1
// xAxis.setLabelCount(7, force: true)
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",]
xAxis.valueFormatter = IndexAxisValueFormatter(values:months)
//Also, you probably want to add:
let leftAxis = barChartView.leftAxis;
leftAxis.enabled = false
leftAxis.drawAxisLineEnabled = false;
leftAxis.drawGridLinesEnabled = false;
leftAxis.axisMinimum = 0.0; // this replaces startAtZero = YES
let rightAxis = barChartView.rightAxis
rightAxis.enabled = false;
rightAxis.drawAxisLineEnabled = true;
rightAxis.drawGridLinesEnabled = false;
rightAxis.axisMinimum = 0.0; // this replaces startAtZero = YES
let l = barChartView.legend
l.enabled = false
barChartView.fitBars = true;
barChartView.animate(xAxisDuration: 0.2, yAxisDuration: 1.0, easingOptionX: .easeInExpo, easingOptionY: .easeInExpo)
setDataCount(count: 7, range: 50)
}
func setDataCount(count: Int, range: Double){
let barWidth = 7.0
let spaceForBar = 10.0
var yVals = [BarChartDataEntry]()
yVals.append(BarChartDataEntry(x: Double(0) * spaceForBar, y: 44.5))
yVals.append(BarChartDataEntry(x: Double(1) * spaceForBar, y: 78.1))
yVals.append(BarChartDataEntry(x: Double(2) * spaceForBar, y: 50.3))
yVals.append(BarChartDataEntry(x: Double(3) * spaceForBar, y: 56.6))
yVals.append(BarChartDataEntry(x: Double(4) * spaceForBar, y: 20.5))
yVals.append(BarChartDataEntry(x: Double(5) * spaceForBar, y: 44.3))
yVals.append(BarChartDataEntry(x: Double(6) * spaceForBar, y: 54.4))
var set1 : BarChartDataSet!
if let count = barChartView.data?.dataSetCount, count > 0{
set1 = barChartView.data?.dataSets[0] as! BarChartDataSet
set1.values = yVals
set1.colors = [UIColor.black,UIColor.orange,UIColor.red,UIColor.green,UIColor.yellow,UIColor.blue,UIColor.gray]
barChartView.data?.notifyDataChanged()
barChartView.notifyDataSetChanged()
}else{
set1 = BarChartDataSet(values: yVals, label: "DataSet")
set1.colors = [UIColor.black,UIColor.orange,UIColor.red,UIColor.green,UIColor.yellow,UIColor.blue,UIColor.gray]
var dataSets = [BarChartDataSet]()
dataSets.append(set1)
let data = BarChartData(dataSets: dataSets)
data.barWidth = barWidth;
barChartView.data = data
}
}
Add the following delegate method of "IAxisValueFormatter"
And assign these delegate.
class xyz : IAxisValueFormatter{
weak var axisFormatDelegate: IAxisValueFormatter?
//add these line in the func...
func doBarChart{
let xAxisValue = lineChartView.xAxis
xAxisValue.valueFormatter = axisFormatDelegate
lineChartView.xAxis.granularityEnabled = true
lineChartView.xAxis.granularity = 1.0
}
//add these method..
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return yvlaues[Int(value) % yvlaues.count]
}
}

How to apply dynamicBehavior on multiple objects simultaneously

I'm trying to use DynamicBehaviors on Label objects I have just created from a Array. For this I use the "For In" loop. All objects get created as expected, but only the last get dynamic.
Maybe I should use the UIDynamicItemGroup, but after many tries, I still don't figure out how to use it.
As you are maybe wondering, I'm new to object oriented programming so I hope it will not be a waste of time for you.
Below the code I have actually.
Thanks in advance.
import UIKit
class ViewController: UIViewController {
var tests:[String] = ["test1","test2","test3","test4","test5","test6","test7","test8","test9","test10","test11"]
var viewLabelArray:UIView!
var label:UILabel!
var color:UIColor!
var animator:UIDynamicAnimator!
var dynamicBehavior:UIDynamicBehavior!
var collisionBehavior:UICollisionBehavior!
var countLabel = 0
override func viewDidLoad() {
super.viewDidLoad()
let size:CGFloat = 50.0
var positionX:CGFloat = 60.0
var positionY:CGFloat = 100.0
for test in tests {
label = UILabel(frame:CGRect(x: positionX, y: positionY, width: size, height: size))
label.center = CGPoint(x: positionX, y: positionY)
label.layer.cornerRadius = size * 0.5
label.layer.masksToBounds = true
label.backgroundColor = color
label.textAlignment = .center
label.textColor = UIColor.white
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 1
label.text = test
self.view.addSubview(label)
countLabel = countLabel + 1
if countLabel == 4 || countLabel == 8 {
positionX = positionX - 140
positionY = positionY + 100
} else {
positionX = positionX + 60
}
let gravity = UIGravityBehavior(items: [label])
let direction = CGVector(dx: 0.0, dy: 1.0)
gravity.gravityDirection = direction
let bounce = UIDynamicItemBehavior(items: [label])
bounce.elasticity = 1
let boundries = UICollisionBehavior(items: [label])
boundries.translatesReferenceBoundsIntoBoundary = true
animator = UIDynamicAnimator(referenceView: self.view)
animator.addBehavior(bounce)
animator.addBehavior(boundries)
animator.addBehavior(gravity)
}
}
}
I modified some line of your code and it's perfectly working for me.
Thanks to Alexander Momchliov
var animatorArray = [UIDynamicAnimator]()
for (i,test) in tests.enumerated() {
//code
let bounce = UIDynamicItemBehavior(items: [label])
bounce.elasticity = 1
let boundries = UICollisionBehavior(items: [label])
boundries.translatesReferenceBoundsIntoBoundary = true
animatorArray.append(UIDynamicAnimator(referenceView: self.view))
animatorArray[i].addBehavior(gravity)
animatorArray[i].addBehavior(bounce)
animatorArray[i].addBehavior(boundries)
}
Screenshot:

iOS Core Plot with Swift - Formatting Axis

Hi I am new to core plot and I have this issue and its bugging me for sometime..
The issue is that both X and Y axis won't show the axis label, axis tile, axis majorlengthinterval, etc.. Basically, I cannot set the axis properties except axis line style. The following is my code.
class testVC: UIViewController, CPTPlotDataSource, CPTPlotDelegate, CPTPlotSpaceDelegate {
var hostView: CPTGraphHostingView!
let xData = ["2","4"]
let yData = ["1","2"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func symbolForScatterPlot(aPlot: CPTScatterPlot, recordIndex index: UInt) -> CPTPlotSymbol {
let dotStyle = CPTPlotSymbol()
dotStyle.size = CGSizeMake(6, 6)
dotStyle.fill = CPTFill(color: CPTColor.blueColor())
dotStyle.symbolType = CPTPlotSymbolType.Ellipse
return dotStyle
}
#IBAction func plotClick(sender: AnyObject) {
let frame = self.view.frame
//add graph
let graph = CPTXYGraph(frame: CGRect(x: 0, y: 50, width: frame.width, height: frame.height - 250))
graph.paddingBottom = 10
graph.paddingLeft = 10
graph.paddingRight = 10
graph.paddingTop = 10
graph.title = "Scatter Plot"
//hostView
hostView = CPTGraphHostingView(frame: graph.frame)
self.view.addSubview(hostView)
//add scatter plot and plot space
var scatterPlot = CPTScatterPlot()
scatterPlot = CPTScatterPlot(frame: hostView.frame)
scatterPlot.delegate = self
scatterPlot.dataSource = self
let plotSpace = graph.defaultPlotSpace as! CPTXYPlotSpace
plotSpace.delegate = self
plotSpace.allowsUserInteraction = true
plotSpace.xRange = CPTPlotRange(location: 0, length: 10)
plotSpace.yRange = CPTPlotRange(location: 0, length: 18)
scatterPlot.dataLineStyle = nil //hide line
graph.addPlot(scatterPlot)
//set axis
let axes: CPTXYAxisSet = CPTXYAxisSet(layer: graph.axisSet!); let x = axes.xAxis; let y = axes.yAxis
let lineStyle = CPTMutableLineStyle()
lineStyle.lineWidth = 3
x!.axisLineStyle = lineStyle; y!.axisLineStyle = lineStyle
x!.title = "X"; y!.title = "Y"
x!.orthogonalPosition = 0; y!.orthogonalPosition = 0
x!.majorIntervalLength = 1; y!.majorIntervalLength = 1
x!.minorTickLength = 4; y!.minorTickLength = 4
hostView.hostedGraph = graph
}
func numberOfRecordsForPlot(plot: CPTPlot) -> UInt {
return 2
}
func numberForPlot(plot: CPTPlot, field fieldEnum: UInt, recordIndex idx: UInt) -> AnyObject? {
if fieldEnum == 0 {
return xData[Int(idx)]
} else {
return yData[Int(idx)]
}
}
You're not setting the axis properties on the one belonging to the graph—you're setting up a copy which then goes away. Try this instead:
let axes = graph.axisSet as? CPTXYAxisSet

Core Plot Swift BarPlot tickLocation always zero

I'm trying to make a Bar Chart using core-plot under Swift, i have a problem making custom labels on xAxis, they're always in tickLocation zero.
Maybe someone can help me, this is my code.
import UIKit
class aaa: UIViewController, CPTPlotDataSource{
var items :[NSNumber] = [10,35,18, 20, 50, 5]
#IBOutlet var scrollView: UIScrollView!
#IBOutlet weak var lblTitle: UILabel!
#IBOutlet weak var lblChartName: UILabel!
#IBOutlet weak var vGraph: CPTGraphHostingView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.contentSize = CGSizeMake(320, 568);
var id: Int=general.idListed
lblTitle.text=general.namListed
items = [10, 35, 18, 20, 50, 5]
var CPDBarWidth:CGFloat = 0.25
var CPDBarInitialX:CGFloat = 0.25
var graph = CPTXYGraph(frame: CGRectZero)
graph.plotAreaFrame.masksToBorder = false
graph.paddingBottom = 50.0
graph.paddingLeft = 50.0
graph.paddingTop = 50.0
graph.paddingRight = 50.0
graph.backgroundColor = UIColor.whiteColor().CGColor
var titleStyle = CPTMutableTextStyle()
titleStyle.color = CPTColor.blackColor()
titleStyle.fontName = "Helvetica-Bold"
titleStyle.fontSize = 16.0
var title : NSString = "January 19 - 24, 2015"
graph.title = title
graph.titleTextStyle = titleStyle
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop
graph.titleDisplacement = CGPointMake(0.0, 40.0)
var xMin : Float = 0
var xMax : Float = Float(items.count) + 1
var yMin : Float = 0
var yMax : Float = maxItemsValue(items) + 5
var plotSpace = graph.defaultPlotSpace as CPTXYPlotSpace
var xRange = plotSpace.yRange.mutableCopy() as CPTMutablePlotRange
var yRange = plotSpace.yRange.mutableCopy() as CPTMutablePlotRange
xRange.setLocationFloat(xMin)
xRange.setLengthFloat(xMax)
yRange.setLocationFloat(yMin)
yRange.setLengthFloat(yMax)
plotSpace.xRange = xRange
plotSpace.yRange = yRange
var aaplPlot = CPTBarPlot()
aaplPlot.barsAreHorizontal = false
var barLineStyle = CPTMutableLineStyle()
barLineStyle.lineColor = CPTColor.lightGrayColor()
barLineStyle.lineWidth = 1
aaplPlot.dataSource = self
aaplPlot.delegate = self
aaplPlot.barWidthScale = 1
aaplPlot.barOffsetScale = 1
aaplPlot.lineStyle = barLineStyle
graph.addPlot(aaplPlot)
var axisTitleStyle = CPTMutableTextStyle()
axisTitleStyle.color = CPTColor.redColor()
axisTitleStyle.fontName = "Helvetica-Bold"
axisTitleStyle.fontSize = 12.0
var axisLineStyle = CPTMutableLineStyle()
axisLineStyle.lineWidth = 4.0
axisLineStyle.lineColor = CPTColor.redColor()
var axisSet = CPTXYAxisSet()
graph.axisSet = axisSet
axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone
axisSet.xAxis.title = "Days of Week"
axisSet.xAxis.titleTextStyle = axisTitleStyle
axisSet.xAxis.titleOffset = 30.0
axisSet.xAxis.majorTickLength = 4
axisSet.xAxis.minorTickLength = 0
axisSet.xAxis.tickDirection = CPTSignNegative
axisSet.xAxis.axisLineStyle = axisLineStyle
var customLabels : NSMutableArray = NSMutableArray (capacity: items.count)
var tickLocations : NSMutableArray = NSMutableArray (capacity: items.count)
var labels : [String] = ["MON","THU","WEN","THR","FRI","SAT"]
var next : Int = 0
var newLabel : CPTAxisLabel
for item in items {
var xlabel : String = labels[next]
next++;
var tstyle : CPTMutableTextStyle = CPTMutableTextStyle()
tstyle.color = CPTColor.blueColor()
tstyle.fontSize = 10
newLabel = CPTAxisLabel(text: xlabel, textStyle: tstyle);
newLabel.setTickLocationFloat(Float(next))
newLabel.offset = 5
customLabels.addObject(newLabel)
tickLocations.addObject(Float(next))
}
axisSet.xAxis.majorTickLocations = NSSet(array: tickLocations)
axisSet.xAxis.axisLabels = NSSet(array: customLabels)
self.vGraph.hostedGraph = graph
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func maxItemsValue(items :[NSNumber])-> NSNumber{
var max : NSNumber=0
for item in items{
if item.floatValue > max.floatValue {
max = item
}
}
return max
}
func numberOfRecordsForPlot(plot: CPTPlot!) -> UInt {
return UInt(items.count)
}
func numberForPlot(plot: CPTPlot!, field fieldEnum: UInt, recordIndex idx: UInt) -> NSNumber! {
switch (fieldEnum) {
case 0:
if (idx < UInt(items.count)) {
return idx + 1
}
break;
case 1:
return items[Int(idx)]
default:
return 1
}
return 1
}
}
You need to set the tickLocation of each new label.
newLabel.tickLocation = next

Resources