How to add background color and rounded corners for Strings in iOS?
like this picture below:
Can't do it with NSAttributedstring
. So, should I use CoreText
? I found this answer but still don't know how to do it.
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.
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])];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With