前言: 今天分享一个很漂亮的功能强大的图表库,希望对有需要的同学,有帮助,喜欢请点个赞,支持一下.谢谢~
在项目中如何加入Swift库请看我的上一篇文章
http://www.jianshu.com/p/fd91c10c9f55
编译环境: Xcode7.3
添加Charts图表库
// 在Podfile中
use_frameworks!
pod 'Charts'
import Charts
创建柱状图
func createLineChartView()
{
chartView = BarChartView.init(frame: CGRectMake(0,64,screenWidth,screenHeight - 64))
chartView.barData
// 签协议
chartView.delegate = self
chartView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(chartView)
}
模拟数据赋值
func setChart(dataPoints: [String],values: [Double]) {
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(value: values[i],xIndex: i)
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(yVals: dataEntries,label: "Units Sold")
let chartData = BarChartData(xVals: months,dataSet: chartDataSet)
// 加上一个界限,演示图中红色的线
let jx = ChartLimitLine(limit: 12.0,label: "I am LimitLine")
chartView.rightAxis.addLimitLine(jx)
chartView.data = chartData
// 自定义颜色
// 例子中有十二个柱状图
// colors 是一个数组,可以给相应的颜色
chartDataSet.colors = [UIColor.blueColor(),UIColor.redColor(),UIColor.cyanColor()]
// API 自带颜色模板
// ChartColorTemplates.liberty()
// ChartColorTemplates.joyful()
// ChartColorTemplates.pastel()
// ChartColorTemplates.colorful()
// ChartColorTemplates.vordiplom()
chartDataSet.colors = ChartColorTemplates.liberty()
/** // 动画效果,简单列举几个,具体请看API case EaseInBack case EaSEOutBack case EaseInOutBack case EaseInBounce case EaSEOutBounce case EaseInOutBounce */
// 加上动画
chartView.animate(yAxisDuration: 1.0,easingOption: .EaseInBounce)
}
还可以保存当前的图表状态,写一个保存按钮
func createRightBarButtonItem()
{
let buttonRight = UIButton.init(type: UIButtonType.Custom)
buttonRight.frame = CGRectMake(0,0,40,40)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: buttonRight)
buttonRight.setTitle("Save",forState: UIControlState.Normal)
buttonRight.addTarget(self,action:#selector(ViewController.save(_:)),forControlEvents: UIControlEvents.TouchUpInside)
}
func save(btn: UIButton)
{
// 保存到相册
chartView.saveToCameraRoll()
print("保存成功")
}
你可能还想实现点击单个立柱实现不同的点击事件
你可以 实现ChartViewDelegate
class ViewController: UIViewController,ChartViewDelegate {
// 在创建的时候签协议
// chartView.delegate = self
// 实现协议方法
func chartValueSelected(chartView: ChartViewBase,entry: ChartDataEntry,dataSetIndex: Int,highlight: ChartHighlight) {
print("\(entry.value) in \(months[entry.xIndex])")
}
这样创建折线图
chartView = LineChartView.init(frame: CGRectMake(0,64,screenHeight - 64))
模拟数据赋值改成如下代码
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(value: values[i],xIndex: i)
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(yVals: dataEntries,label: "Units Sold")
let chartData = LineChartData(xVals: months,dataSet: chartDataSet)
总结: 图标支持缩放点击,这里我只给出了两种样式的图标代码示例,详情请看官方API和Demo请点击
考虑到文章可能思路混乱有些地方不清楚我会放上github地址,方便大家学习下载查看请点击