swift中的图表数据
Posted
技术标签:
【中文标题】swift中的图表数据【英文标题】:Graph's data in swift 【发布时间】:2016-02-07 10:13:57 【问题描述】:几个月来,我一直在快速开发应用程序,但我不知道如何将数据传递到图表。所以基本上我所拥有的是一个内部有一个数组的视图控制器和一个包含图表的 UIView。我想要做的是 UIView 中的图形绘制 ViewController 中的数组。所以我想要的是将视图控制器中数组dataMoneyTracker1中的数据传递给UIView中的数组graphpoints,或者我可以从uiview访问到视图控制器中的数组。
感谢您的回答!
这是我的代码:
查看控制器
import UIKit
class GonDetail2ViewController: UIViewController
var dataMoneyTracker1 = [Int]()
@IBOutlet var View1: UIView!
用户界面
import UIKit
class GonGraphUIView: UIView
var graphPoints = [Int]()
override func drawRect(rect: CGRect)
let width = rect.width
let height = rect.height
let margin:CGFloat = 20.0
let columnXPoint = (column:Int) -> CGFloat in
//Calculate gap between points
let spacer = (width - margin*2 - 4) /
CGFloat((self.graphPoints.count - 1))
var x:CGFloat = CGFloat(column) * spacer
x += margin + 2
return x
let topBorder:CGFloat = 60
let bottomBorder:CGFloat = 50
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.maxElement()
let columnYPoint = (graphPoint:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint) /
CGFloat(maxValue!) * graphHeight
y = graphHeight + topBorder - y // Flip the graph
return y
UIColor.whiteColor().setFill()
UIColor.whiteColor().setStroke()
//set up the points line
let graphPath = UIBezierPath()
//go to start of line
graphPath.moveToPoint(CGPoint(x:columnXPoint(0),
y:columnYPoint(graphPoints[0])))
//add points for each item in the graphPoints array
//at the correct (x, y) for the point
for i in 1..<graphPoints.count
let nextPoint = CGPoint(x:columnXPoint(i),
y:columnYPoint(graphPoints[i]))
graphPath.addLineToPoint(nextPoint)
graphPath.stroke()
graphPath.lineWidth = 2.0
graphPath.stroke()
//Draw the circles on top of graph stroke
for i in 0..<graphPoints.count
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
point.x -= 5.0/2
point.y -= 5.0/2
let circle = UIBezierPath(ovalInRect:
CGRect(origin: point,
size: CGSize(width: 5.0, height: 5.0)))
circle.fill()
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
// Drawing code
*/
【问题讨论】:
【参考方案1】:UIViewController 可以用这个变量重新定义:
@IBOutlet var View1: GonGraphUIView!
在GonGraphUIView
var graphPoints:[Int]?
然后在drawRect
if let graphPoints = graphPoints
// draw the graph
else do nothing
所以 UIViewController 可以说
View1.graphPoints = dataMoneyTracker1
View1.setneedsDisplay()
【讨论】:
谢谢!这真的很有帮助!【参考方案2】:有两种方法可以解决这个问题。
最简单的方法是在任何类之外定义var dataMoneyTracker1 = [Int]()
,然后您就可以随时访问它。
或者您可以将其设为类变量,然后您可以访问它:
class GonDetailViewController: UIViewController
static var dataMoneyTracker1 = [Int]()
class GonGraphUIView : UIView
var graphPoints = GonDetailViewController.dataMoneyTracker1
【讨论】:
以上是关于swift中的图表数据的主要内容,如果未能解决你的问题,请参考以下文章
如何更改 xAxis 标签 iOS 图表 (Swift 2.3)
我们需要在Swift 3中使用哪个Pod来实现iOS中的图表?
📈📈📈📈📈iOS 图表框架 AAChartKit ---强大的高颜值数据可视化图表框架,支持柱状图条形图折线图曲线(代码