- Charts
-
界面展示
1. 使用pod将Charts导入项目中
2. 步骤
(1)新建视图
- 在故事版中拖入1个ViewController视图
- 在新视图中拖入2个View,垂直排布平分整个视图
-
选中其中一个View并之设置为BarChartView,另一个View为PieChartView
备注
:设置View为BarChartView何PieChartView时,找不到BarChartView和PieChartView,原因可能是Charts导入项目后需要重新编译项目。
(2)创建视图对应的控制器MyChartViewController.swift
(3)视图和控制器绑定,并在控制器中添加视图中两个view控件的引用
2. 具体实现
(1)MyChartViewController.swift
//
// MyChartViewController.swift
// JackUChat
//
// Created by 徐云 on 2019/1/16.
// Copyright © 2019 Liy. All rights reserved.
//
import UIKit
import Charts
class MyChartViewController: UIViewController {
@IBOutlet weak var barChartView: BarChartView!
@IBOutlet weak var pieChartView: PieChartView!
var months:[String]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
let percents = [20.0,18.0,25.0,19.0,16.0,20.0,17.0,17.0,15.0,21.0,20.0,13.0]
setBarChart(dataPoints: months, values: percents)
setPieChart(dataPoints: months, values: percents)
}
func setBarChart(dataPoints:[String],values:[Double]) {
//barChartView.noDataText = "该处显示无数据时的显示文字,不设置则显示默认信息"
var dataEntries:[BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: values[i], y: Double(i))
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")
let chartData = BarChartData(dataSet: chartDataSet)
barChartView.data = chartData
}
func setPieChart(dataPoints:[String],values:[Double]) {
var dataEntries:[PieChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = PieChartDataEntry(value: values[i], label: months[i])
dataEntries.append(dataEntry)
}
let chartDataSet = PieChartDataSet(values: dataEntries, label: "Units Sold")
let chartData = PieChartData(dataSet: chartDataSet)
pieChartView.data = chartData
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
备注
:自定义charts图表样式可参考使用Charts实现图表-进阶