Search code examples
ioscore-plot

CorePlot - multiLine attributed label


I am trying to create a custom label for coreplot using NSAttributedString. Everything works fine when my strings have 1 line.

The problem occurs when I want to have 2 line strings using code:

NSMutableAttributedString* remFinalLabel = [remAttrStr mutableCopy];
NSMutableAttributedString *newLineAttrStr = [[NSMutableAttributedString alloc]initWithString:@"\n"];
[remFinalLabel appendAttributedString:newLineAttrStr];
[remFinalLabel appendAttributedString:rem2AttrStr];

The result looks like that: not even first string is properly displayed. How can I set the number of lines in custom label?

enter image description here

My code to create labels:

NSMutableArray* labelsStrings = [NSMutableArray arrayWithObjects:strAttr1, strAttr2, strAttr3, nil];
NSMutableArray *ticksLocations = [NSMutableArray arrayWithObjects:@0.5, @1.5, @2.5, nil];
NSMutableArray* customLabels = [[NSMutableArray alloc] init];
NSUInteger labelLocation = 0;

@try {
    for (NSNumber *tickLocation in ticksLocations) {
        NSAttributedString* currentLabel = [labelsStrings objectAtIndex:labelLocation];

        CPTTextLayer *txtLayer = [[CPTTextLayer alloc] initWithAttributedText:currentLabel];
        CPTAxisLabel* newLabel = [[CPTAxisLabel alloc] initWithContentLayer:txtLayer];

        newLabel.tickLocation = tickLocation;
        newLabel.offset = 0.0f;
        newLabel.alignment = CPTAlignmentLeft;
        [customLabels addObject:newLabel];
        labelLocation++;
    }
}
@catch (NSException * e) {
    DLog(@"An exception occurred while creating date labels for x-axis");
}
@finally {
    y.axisLabels =  [NSSet setWithArray:customLabels];
}
y.majorTickLocations = [NSSet setWithArray:ticksLocations];

Solution

  • You can achieve this by setting the frame of content layer of your CPTAxisLabel.

    Try this:-

        CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:@"Your Text Here" textStyle:@"Text Style"];
        [label.contentLayer setFrame:CGRectMake(0, 0, 40, 40)]; //change this frame according to your requirement
    

    Happy Coding..!!