如何在CorePlot中设置自定义字符串坐标轴刻度?
在CorePlot中设置非数值坐标轴刻度
完全可以,CorePlot提供了几种简便的方式实现将坐标轴刻度从数值替换为自定义字符串,下面是两种常用方案:
方法一:自定义标签格式化器
你可以创建一个NSFormatter子类,通过重写stringForObjectValue:方法,把刻度对应的数值映射成目标字符串:
@interface CustomAxisFormatter : NSFormatter @end @implementation CustomAxisFormatter - (NSString *)stringForObjectValue:(id)obj { if ([obj isKindOfClass:[NSNumber class]]) { NSInteger value = [(NSNumber *)obj integerValue]; // 按数值匹配对应字符串 switch (value) { case 1: return @"A"; case 2: return @"B"; case 3: return @"C"; case 4: return @"D"; default: return @""; } } return @""; } // 其他Formatter方法按需实现,这里可以空实现 - (BOOL)getObjectValue:(out id __nullable * __nullable)obj forString:(NSString *)string errorDescription:(out NSString * __nullable * __nullable)error { return NO; } @end
接着把这个格式化器绑定到坐标轴上,同时指定刻度的数值位置:
CPTXYAxis *xAxis = [(CPTXYAxisSet *)graph.axisSet xAxis]; CustomAxisFormatter *formatter = [[CustomAxisFormatter alloc] init]; xAxis.labelFormatter = formatter; // 设置要显示的刻度数值点 xAxis.majorTickLocations = [NSSet setWithObjects:@1, @2, @3, @4, nil];
方法二:直接绑定自定义标签数组
如果刻度位置固定且数量不多,直接给坐标轴的majorTickLabels赋值字符串数组更直接,注意标签顺序要和刻度位置一一对应:
CPTXYAxis *xAxis = [(CPTXYAxisSet *)graph.axisSet xAxis]; // 先设置刻度的数值位置 xAxis.majorTickLocations = [NSSet setWithObjects:@1, @2, @3, @4, nil]; // 创建对应标签数组 NSArray *customLabels = @[@"A", @"B", @"C", @"D"]; // 把字符串转成CPTTextLayer对象并赋值 xAxis.majorTickLabels = @[ [[CPTTextLayer alloc] initWithText:customLabels[0]], [[CPTTextLayer alloc] initWithText:customLabels[1]], [[CPTTextLayer alloc] initWithText:customLabels[2]], [[CPTTextLayer alloc] initWithText:customLabels[3]] ];
如果用Swift开发,思路完全一致,只需要把代码转换成Swift语法即可,比如自定义Formatter子类,或者创建CPTTextLayer数组赋值给坐标轴的majorTickLabels属性。
内容的提问来源于stack exchange,提问作者N0ctrn
相关产品推荐
相关产品推荐

