我想在Github上使用piechart danielgindi / Charts库。 我的代码是这样的:
import UIKit
import Charts
class ChartViewController: UIViewController {
@IBOutlet weak var pieChartView: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
// 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(dataPoints: months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry1 = PieChartDataEntry(value: Double(i), label: dataPoints[i], data: dataPoints[i] as AnyObject)
dataEntries.append(dataEntry1)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Units Sold")
let pieChartData = PieChartData(dataSet: pieChartDataSet)
pieChartView.data = pieChartData
var colors: [UIColor] = []
for _ 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
}
}
但是当我运行它时,请分解这一行:
pieChartView.data = pieChartData
我没有在任何图表库之前使用,但是我必须使用一个项目。这个图书馆或其他图书馆对我来说无关紧要。如果您知道回答我的问题,请帮助我解决。或者您可以告诉我另一个与switf 3兼容的库。谢谢。
答案 0 :(得分:6)
我以编程方式初始化pieChartView
并将其添加到子视图中。代码运行正常,不会崩溃。我做了必要的修改并在下面添加了它:
import UIKit
import Charts
class ChartViewController: UIViewController {
var pieChartView: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
// 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]
pieChartView = PieChartView(frame: self.view.bounds)
self.view.addSubview(pieChartView!)
setChart(dataPoints: months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry1 = PieChartDataEntry(value: values[i], label: dataPoints[i])
dataEntries.append(dataEntry1)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Units Sold")
let pieChartData = PieChartData(dataSet: pieChartDataSet)
pieChartView.data = pieChartData
var colors: [UIColor] = []
for _ 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
}
}