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

1

9

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.

Sarad answered 6/9, 2017 at 7:31 Comment(6)
Possible duplicate of how to use rounded corner label in iphone,UILabel Round CornersBouse
@NicolasMiari The corners of specific text, not UILabelSarad
I see, individual words inside a single text view... My bad.Bouse
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).Bouse
@NicolasMiari still, thanks for helpingSarad
Possible duplicate of How to set NSString's background cornerRadius on iOS7Kinescope
U
2

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])];
Unproductive answered 6/9, 2017 at 7:50 Comment(8)
Well, I want to make rounded corners for specific text, not UILabel. but thanksSarad
Text cannot appear as it is. It could be a text of a UILabel, UITextView, UIButton etc. but a text cannot be visual as it is.Unproductive
yes. maybe I should use CoreText to do this. I just don't know how.Sarad
I've updated the answer. You don't have to use CoreText. TTT will give you many options in ease. It's a really powerful library used in many apps.Unproductive
Interesting... is there a "corner radius" attribute as well?Bouse
I've added an example usage.Unproductive
Also, don't forget to include 'clipsToBounds = true'Murcia
Hi, do you have a swift example for the TTTAttributedLabel example? Thanks :)Subdivision

© 2022 - 2024 — McMap. All rights reserved.