Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to highlight only text in UILabel - IOS

I just want to highlight only text in UILabel, I have tried by giving backgroundColor for label, but it is highlighting the empty spaces also looks not good. So Is there any way to highlight text without resizing UILabel.

Please check the image, here labels are bigger than the text (center aligned)

enter image description here

Thanx.

like image 906
Newbee Avatar asked May 06 '13 09:05

Newbee


2 Answers

Most of the other solutions don't consider text that spans multiple lines while still only highlighting the text, and they are all pretty hacky involving extra subviews.

An iOS 6 and later solution is to use attributed strings:

NSMutableAttributedString *s =
     [[NSMutableAttributedString alloc] initWithString:yourString];

[s addAttribute:NSBackgroundColorAttributeName
          value:[UIColor greenColor]
          range:NSMakeRange(0, s.length)];

label.attributedText = s;
like image 145
Mike Weller Avatar answered Nov 15 '22 22:11

Mike Weller


This will add a subview behind the text, with the correct size:

CGSize size= [[label text] sizeWithFont:[UIFont systemFontOfSize:18.0]];
NSLog(@"%.1f | %.1f", size.width, size.height);
NSLog(@"%.1f | %.1f", label.frame.size.width, label.frame.size.height);

UIView *highlightView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
[highlightView setBackgroundColor:[UIColor greenColor]];
[self.view insertSubview:highlightView belowSubview:label];
[highlightView setCenter:label.center];

And don't forget: [label setBackgroundColor:[UIColor clearColor]];

like image 3
xapslock Avatar answered Nov 16 '22 00:11

xapslock