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

前端 未结 1 555
我寻月下人不归
我寻月下人不归 2021-02-10 02:07

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

like this picture below:

Can\'t do it with NSAttributedstring. So, shou

1条回答
  •  长情又很酷
    2021-02-10 03:04

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

    0 讨论(0)
提交回复
热议问题