如何设置数据源?

时间:2017-02-07 23:51:08

标签: objective-c core-plot

我正在使用最新版本的CorePlot根据this website的教程创建折线图。但是,我对如何基于数组实际设置数据源感到困惑。本质上,散点图需要绘制数组中的所有值,y轴是数组中每个元素的值,x轴是数组中每个元素的索引。我怎么能做到这一点?

.m文件:

- (void)viewDidLoad
{
[super viewDidLoad];

CPTGraphHostingView* hostView = [[CPTGraphHostingView alloc] initWithFrame:self.view.frame];
[self.view addSubview: hostView];

CPTGraph* graph = [[CPTXYGraph alloc] initWithFrame:hostView.bounds];
hostView.hostedGraph = graph;

CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;

[plotSpace setYRange: [CPTPlotRange plotRangeWithLocation:@0 length:@16]];
[plotSpace setXRange: [CPTPlotRange plotRangeWithLocation:@-4 length:@8]];

CPTScatterPlot* plot = [[CPTScatterPlot alloc] initWithFrame:CGRectZero];

plot.dataSource = self;

[graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];
}

- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plotnumberOfRecords
{
return 9; 
}

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
int x = index - 4;

if(fieldEnum == CPTScatterPlotFieldX)
{
    return [NSNumber numberWithInt: x];
}

else
{
    return [NSNumber numberWithInt: x * x];
}
}

@end

.h文件:

@interface FirstViewController : UIViewController

@end

@interface CorePlotExampleViewController : UIViewController  <CPTScatterPlotDataSource>

@end

1 个答案:

答案 0 :(得分:1)

您没有显示包含数据的数组的位置,但假设它是NSArray NSNumber,您只需要返回正确的x和y numberForPlot方法中的值如下:

if (fieldEnum == CPTScatterPlotFieldX)
{
    // x values go from -4 to 4 (based on how you set up your plot space Xrange)
    return [NSNumber numberWithInt:(index - 4)];
}
else
{
    // y value is the contents of the array at the given index
    return [dataArray objectAtIndex:index];
}