如何在iOS中为字符串添加背景颜色和圆角? [英] How to add background color and rounded corners for Strings in iOS?

查看:44
本文介绍了如何在iOS中为字符串添加背景颜色和圆角?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在iOS中为字符串添加背景颜色和圆角?

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

像下面的这张照片一样:

like this picture below:

使用 NSAttributedstring 无法做到.因此,我应该使用 CoreText 吗?我找到了此答案,但仍然不知道该怎么做./p>

Can't do it with NSAttributedstring. So, should I use CoreText? I found this answer but still don't know how to do it.

推荐答案

字符串只是文本格式的数据,不是可视的.您需要标签,这些标签在那里.然后将您的字符串设置为该标签.

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.

如果要使文本视图内的单个文本变彩色,可以使用TTTAttributedLabel并将带有背景的属性文本设置为单个文本.

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.

您可以在此处找到TTTAttributedLabel.

You can find TTTAttributedLabel here.

CornerRadius : kTTTBackgroundCornerRadiusAttributeName

背景颜色: kTTTBackgroundFillColorAttributeName

用法示例:

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:TTTAttributedTestString()];

[string addAttribute:kTTTBackgroundFillColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [string length])];

这篇关于如何在iOS中为字符串添加背景颜色和圆角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆