Question

I am trying to show text above CALayer but somehow I am not able to achieve it. I have used following code:

- (void)drawRect:(CGRect)rect
{
    self.layer.sublayers = nil;
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);

    // Code to show grid lines clipped

    CGRect overallRectForBarItem = CGRectMake(20, 20, 176, 35);
    CAShapeLayer *barItemShape = [CAShapeLayer layer];
    barItemShape.frame = overallRectForBarItem;
    barItemShape.path = [UIBezierPath bezierPathWithRect:overallRectForBarItem].CGPath;
    barItemShape.strokeColor = [UIColor lightGrayColor].CGColor;
    barItemShape.fillColor = [UIColor lightGrayColor].CGColor;
    [self.layer addSublayer:barItemShape];

    [self drawTextForBarItem:@"TESTING" inRect:CGRectMake(100, 40, 35, 0)];

    // Other code clipped

    CGContextRestoreGState(ctx);
}

-(void) drawTextForBarItem:(NSString*)barItemTitle inRect:(CGRect)rect
{
    float actualFontSize = 14.0;
    UIFont *font = [ISUtility getSystemFont:actualFontSize];
    CGSize size = [barItemTitle sizeWithFont:font];
    NSMutableParagraphStyle *paragraphStyle = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentRight;
    [barItemTitle drawInRect:CGRectMake(rect.origin.x, rect.origin.y - size.height/2, rect.size.width, size.height) withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:[UIColor blueColor], NSParagraphStyleAttributeName:paragraphStyle}];
}

Following is the screen shot of simulator.Screenshot

I have also tried zPosition but no use.

barItemShape.zPosition = -1000;
Was it helpful?

Solution

The most possible cause of you issue is that you creating CGContextRef but adding sublayer when you need to draw lightgray rectangle. I think, that it would be more consistant to draw your rectange with CoreGraphics functions and that draw your text.

To be more detailed, it seems that you drawing text in current layer but adding sublayer that will be above your text.

For instance, you can use this code to give it a try:

UIColor * redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];

CGContextSetFillColorWithColor(context, redColor.CGColor);
CGContextFillRect(context, self.bounds);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top