swift开发笔记13 - 添加图表(饼状图)

前端之家收集整理的这篇文章主要介绍了swift开发笔记13 - 添加图表(饼状图)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用图表类库: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

猜你在找的Swift相关文章