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

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...