2017-02-07 185 views
0

我正在使用最新版本的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

你沒有表現出其中包含數據的陣列設置,但假設它是NSNumberNSArray,你只需要在您的numberForPlot方法中返回正確的x和y值,如下所示:

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]; 
} 
相關問題