3254523
3254523

Reputation: 3026

draw a background color for a UILabel frame where text is present'

I'm trying to figure out a way to get a background color of a UILabel to draw only where text is present. I'm planning to use drawTextInRect, but i need to figure out how to track the text bounds

- (void) drawTextInRect:(CGRect)rect
{
 /* do some custom drawings here */

 [super drawTextInRect:rect];
}

enter image description here

does anyone have any idea how to get this done? thanks

Upvotes: 1

Views: 1375

Answers (1)

ukim
ukim

Reputation: 2465

Use attributed string in your label:

NSAttributedString * text =
[[NSAttributedString alloc]initWithString:@"This is a tring"
                               attributes:@{NSBackgroundColorAttributeName : [UIColor greenColor]}];
_label.attributedText = text;

If you want it to be transparent, set alpha value of the color < 1. You should also set opaque to NO.

NSAttributedString * text =
[[NSAttributedString alloc]initWithString:@"This is a tring."
                               attributes:@{NSBackgroundColorAttributeName : [UIColor colorWithRed:0 green:1 blue:0 alpha:0.2]}];
_label.opaque = NO;
_label.attributedText = text;

Upvotes: 3

Related Questions