6

How to add background color and rounded corners for Strings in iOS?

like this picture below:

enter image description here

Can't do it with NSAttributedstring. So, should I use CoreText? I found this answer but still don't know how to do it.

Meniny
  • 570
  • 5
  • 18
  • Possible duplicate of [how to use rounded corner label in iphone,UILabel Round Corners](https://stackoverflow.com/questions/8530115/how-to-use-rounded-corner-label-in-iphone-uilabel-round-corners) – Nicolas Miari Sep 06 '17 at 07:49
  • 1
    @NicolasMiari The corners of specific text, not UILabel – Meniny Sep 06 '17 at 07:51
  • I see, individual words inside a single text view... My bad. – Nicolas Miari Sep 06 '17 at 07:54
  • I have no idea how to achieve that effect, but it looks low-level enough to grant taking a look at CoreText indeed (which I have never researched yet). – Nicolas Miari Sep 06 '17 at 07:55
  • @NicolasMiari still, thanks for helping – Meniny Sep 06 '17 at 07:55
  • Possible duplicate of [How to set NSString's background cornerRadius on iOS7](https://stackoverflow.com/questions/21857408/how-to-set-nsstrings-background-cornerradius-on-ios7) – karthikeyan Sep 06 '17 at 08:22

1 Answers1

1

String is just a data in text format, it's not visual. You need labels, those are labels there. And then set your string to that label.

let label = UILabel()
label.backgroundColor = .green
label.text = "Label" // You set your string to your label
label.layer.cornerRadius = 5
label.layer.borderColor = .clear
label.layer.borderWidth = 1
label.layer.clipsToBounds = true

Code above creates a label and sets everything you need to achieve it like in the picture. Now you need to add this label into your view or you can set these properties to an existing label you got.

EDIT:

If you want to make individual text inside a text view colorful, you can use TTTAttributedLabel and set an attributed text with background to individual pieces of text.

You can find TTTAttributedLabel here.

CornerRadius: kTTTBackgroundCornerRadiusAttributeName

BackgroundColor: kTTTBackgroundFillColorAttributeName

Example usage:

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:TTTAttributedTestString()];

[string addAttribute:kTTTBackgroundFillColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [string length])];
Ksenya
  • 89
  • 3
  • 13
asanli
  • 316
  • 1
  • 12