Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

core-text

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.

like image 773
Meniny Avatar asked Sep 06 '17 07:09

Meniny


People also ask

How do you make rounded corners in swift?

Make UIImageView Corners RoundedSetting the corner radius to 100 will make the image view completely rounded. Try different corner radius like 10, 20, 30, 40 to get image corners of different radius. To make the image border and visible I will set the borderWidth and the borderColor.


1 Answers

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])];
like image 72
asanli Avatar answered Oct 12 '22 22:10

asanli