在我的iPhone应用程序中,我有一个带有两个独立条形图的视图。每个图都有不同数量的数据元素。我想用适当的数据标记每个图中的每个条,但显然“dataLabelForPlot”方法只允许一个“CPTTextLayer”实例。我想让CPTTextLayer成为情节及其数据的函数。
图表具有单独的标识符:“Bar Plot 1”和“Bar Plot 2”。我可以在“numberOfRecordsForPlot”和“numberForPlot”方法中使用条件if语句,但它在“dataLabelForPlot”方法中失败,错误表明“label”是未使用的变量。看到它在条件语句中定义,对我来说似乎很奇怪。
我的代码如下所示:
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
if (plot.identifier == @"Bar Plot 1") {
return 5; }
else { return 4; }
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSDecimalNumber *num = nil;
if (plot.identifier == @"Bar Plot 1") {
switch ( fieldEnum ) {
case CPTBarPlotFieldBarLocation:
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
break;
case CPTBarPlotFieldBarTip:
num = (NSDecimalNumber *)[dataTemp1 objectAtIndex:index];
break;
}
}
else {
switch ( fieldEnum ) {
case CPTBarPlotFieldBarLocation:
num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
break;
case CPTBarPlotFieldBarTip:
num = (NSDecimalNumber *)[dataTemp2 objectAtIndex:index];
break;
}
}
return num;
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index {
if (plot.identifier == @"Bar Plot 1") {
CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:@"%@", [dataTemp1 objectAtIndex:index]]];
}
else { CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:@"%@", [dataTemp2 objectAtIndex:index]]]; }
CPTMutableTextStyle *textStyle = [label.textStyle mutableCopy];
textStyle.color = [CPTColor redColor];
label.textStyle = textStyle;
[textStyle release];
return [label autorelease];
}
答案 0 :(得分:3)
您已在每个if和else块中声明label
,使其成为这些块的本地。在if语句之前移动变量声明。
CPTTextLayer *label;
if (plot.identifier == @"Bar Plot 1") {
label = ...;
}
else {
label = ...;
}
return [label autorelease];
答案 1 :(得分:2)
plot.identifier == @"Bar Plot 1"
应该是:
[plot.identifier isEqualToString: @"Bar Plot 1"