ioscore-text

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


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.


Solution

  • 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])];