自定义CorePlot label及majorGridLine莫名其妙消失的Bug

    今天在项目中为了实现一个可以显示自定义样式的x轴label,整了我一个下午,搞死我了。先上图:

    自定义CorePlot label及majorGridLine莫名其妙消失的Bug_第1张图片

    图中的表格可以左右拖动,不允许上下拖动。而且只允许显示当前三十天的数据,且今天的标签显示白色。

设置corePlot可拖动:

 plotSpace.allowsUserInteraction = YES;

设置x显示的范围:

plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(8 * oneDay)length:CPTDecimalFromInt(23 * oneDay)];


设置x轴拖动范围:

plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(31 * oneDay)];

禁止corePlot缩放(Self是CPTGraphHostingView):

[self setAllowPinchScaling:NO];//禁止缩放


自定义label:

x.axisLabels = [self buildLabelTitle];
x.labelingPolicy = CPTAxisLabelingPolicyNone;

//构建30天的label样式
- (NSMutableSet*)buildLabelTitle
{
    NSMutableSet *newAxisLabels = [NSMutableSet set];
    
    CPTMutableTextStyle *textStyleB = [CPTMutableTextStyle textStyle];
    textStyleB.color = [CPTColor colorWithComponentRed:CPTFloat((float)0x09/0xFF) green:CPTFloat((float)0x31/0xFF) blue:CPTFloat((float)0x4A/0xFF) alpha:CPTFloat(1.0)];
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:@"MM.dd"];

    int n = 1;
    for ( NSUInteger i = 29; i > 0; i--) //从今起前29天
    {
        NSTimeInterval secondsPerDay = 24 * 60 * 60 * i;
        NSDate *ago = [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay];
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:[dateFormatter stringFromDate:ago]
                                                          textStyle:textStyleB];
        [ago release];
        newLabel.tickLocation = CPTDecimalFromUnsignedInteger(n++ * oneDay);
        newLabel.offset = 5;
        [self.locationLabels addObject:[NSNumber numberWithInt:(n-1) * oneDay]];
        [newAxisLabels addObject:newLabel];
        [newLabel release];
    }
    
    //今天
    CPTMutableTextStyle *textStyleW = [CPTMutableTextStyle textStyle];
    textStyleW.color = [CPTColor whiteColor];
    CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:@"今日" textStyle:textStyleW];
    newLabel.tickLocation = CPTDecimalFromUnsignedInteger(oneDay * n);
    [self.locationLabels addObject:[NSNumber numberWithInt:(n) * oneDay]];
    newLabel.offset = 5;
    [newAxisLabels addObject:newLabel];
    [newLabel release];
    
    return newAxisLabels;
}

但是写好后发现majorGridLine不见了,之后各种折腾后终于找到原因是:

CPTAxisLabelingPolicyNone       No labels provided; user sets labels and tick locations.

设置这个属性是要自己重新定义majorGridLine位置的

所以需要使用:

x.majorTickLocations = [NSSet setWithArray:locationLabels];


结果为:

自定义CorePlot label及majorGridLine莫名其妙消失的Bug_第2张图片



你可能感兴趣的:(自定义CorePlot label及majorGridLine莫名其妙消失的Bug)