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

怎甘沉沦 提交于 2021-02-06 12:51:18

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/46069300/how-to-add-background-color-and-rounded-corners-for-strings-in-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!