使用图表类库:http://www.appcoda.com/ios-charts-api-tutorial/
下载其类库,解压缩有找到charts目录,拷贝到项目文件夹根目录下,如下图:
在charts目录中把Charts.xcodeproj 文件拖到Xcode项目中如下图:
点击 上图link binary with libraries 中的加号,添加 charts.framework到项目中,至此完成类库添加。
在viewcontroller中引入类库:
import Charts
添加饼状图示例:
import UIKit import Charts class ProjectOutlineViewController: UIViewController { // var cubChartView: BarChartView! var pieChartView: PieChartView! override func viewDidLoad() { super.viewDidLoad() pieChartView = PieChartView(frame: CGRect(x: 0,y: 0,width: 300,height: 500)) view.addSubview(pieChartView) // Do any additional setup after loading the view. let months = ["Jan","Feb","Mar","Apr","May","Jun"] let unitsSold = [20.0,4.0,6.0,3.0,12.0,16.0] setChart(months,values: unitsSold) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setChart(dataPoints: [String],values: [Double]) { var dataEntries: [ChartDataEntry] = [] for i in 0..<dataPoints.count { let dataEntry = ChartDataEntry(value: values[i],xIndex: i) dataEntries.append(dataEntry) } let pieChartDataSet = PieChartDataSet(yVals: dataEntries,label: "Units Sold") let pieChartData = PieChartData(xVals: dataPoints,dataSet: pieChartDataSet) pieChartView.data = pieChartData var colors: [UIColor] = [] for i in 0..<dataPoints.count { let red = Double(arc4random_uniform(256)) let green = Double(arc4random_uniform(256)) let blue = Double(arc4random_uniform(256)) let color = UIColor(red: CGFloat(red/255),green: CGFloat(green/255),blue: CGFloat(blue/255),alpha: 1) colors.append(color) } pieChartDataSet.colors = colors /* let lineChartDataSet = LineChartDataSet(yVals: dataEntries,label: "Units Sold") let lineChartData = LineChartData(xVals: dataPoints,dataSet: lineChartDataSet) lineChartView.data = lineChartData */ } }
饼状图效果如下:
http://www.appcoda.com/ios-charts-api-tutorial/
原文链接:https://www.f2er.com/swift/325630.html