我在 Swift 中使用 CorePlot( https://github.com/core-plot/core-plot )。 为了在 iOS 上制作饼图,我通过将 Obj-C 代码转换为 swift 编写如下。 我可以查看图表标题,但无法绘制饼图。
通过查看 NSlog,我发现显然没有调用“numberForPlot”函数。
我应该如何重写它?
我的代码如下所示: View Controller .swift
import UIKit
class ViewController: UIViewController, CPTPieChartDataSource, CPTPieChartDelegate{
@IBOutlet var graphView : CPTGraphHostingView
var dataForChart = NSNumber[]();
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var graph = CPTXYGraph(frame:self.graphView.bounds);
self.graphView.hostedGraph = graph;
graph.title = "Graph Title";
graph.axisSet = nil;
var pieChart = CPTPieChart();
pieChart.pieRadius = 80.0;
pieChart.dataSource = self;
pieChart.delegate = self;
graph.addPlot(pieChart);
self.dataForChart = [40, 30, 20, 10];
self.view.addSubview(self.graphView);
println("self.view.addSubview");
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfRecordsForPlot(plot:CPTPlot)-> Int {
println("numberOfRecordsForPlot");
return self.dataForChart.count;
}
func numberForPlot(plot:CPTPlot, fieldEnum:Int, index:Int) -> NSNumber {
println("numberForPlot");
return self.dataForChart[index] as NSNumber;
}
}
这里是“所有输出”。
self.view.addSubview
numberOfRecordsForPlot
numberOfRecordsForPlot
numberOfRecordsForPlot
numberOfRecordsForPlot
非常感谢任何帮助,谢谢!
附言
以前的 Obj-C 代码
- (void)viewDidLoad
{
[super viewDidLoad];
CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc]
initWithFrame:CGRectMake(0, 0, 320, 320)];
CPTXYGraph *graph = [[CPTXYGraph alloc] initWithFrame:hostingView.bounds];
hostingView.hostedGraph = graph;
graph.title = @"Graph Title";
graph.axisSet = nil;
CPTPieChart *pieChart = [[CPTPieChart alloc] init];
pieChart.pieRadius = 80.0;
pieChart.dataSource = self;
pieChart.delegate = self;
[graph addPlot:pieChart];
self.pieChartData = [NSMutableArray arrayWithObjects:
[NSNumber numberWithDouble:40.0],
[NSNumber numberWithDouble:30.0],
[NSNumber numberWithDouble:20.0],
[NSNumber numberWithDouble:10.0],
nil];
[self.view addSubview:hostingView];
}
并且,这是返回的“numberOfRecordsForPlot”。
func numberOfRecordsForPlot(plot:CPTPlot)-> Int {
println("self.dataForChart.count: \(self.dataForChart.count)");
return self.dataForChart.count;
}
输出
self.view.addSubview
self.dataForChart.count: 4
self.dataForChart.count: 4
self.dataForChart.count: 4
self.dataForChart.count: 4
最佳答案
尝试像这样声明数据源方法:
func numberOfRecordsForPlot(plot: CPTPlot!) -> UInt {}
func numberForPlot(plot: CPTPlot!, field: UInt, recordIndex: UInt ) -> AnyObject! {}
签名必须与 Objective-C 声明完全匹配,否则将不会被调用。
关于ios - Swift 中的 CorePlot 无法调用 “numberForPlot”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24806059/