Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
489 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...