如何为iOS中的字符串添加背景色和圆角?
How to add background color and rounded corners for Strings in iOS?
如何为 iOS 中的字符串添加背景颜色和圆角?
喜欢下面这张图:
NSAttributedstring
无法做到。那么,我应该使用 CoreText
吗?我找到了 this answer 但仍然不知道该怎么做。
字符串只是一种文本格式的数据,它不是可视化的。你需要标签,那里有标签。然后将您的字符串设置为该标签。
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
上面的代码创建了一个标签并设置了实现它所需的一切,如图中所示。现在您需要将此标签添加到您的视图中,或者您可以将这些属性设置为您获得的现有标签。
编辑:
如果要使文本视图中的单个文本具有彩色,可以使用 TTTAttributedLabel 并为单个文本片段设置带背景的属性文本。
您可以找到 TTTAttributedLabel here。
圆角半径: kTTTBackgroundCornerRadiusAttributeName
背景颜色: kTTTBackgroundFillColorAttributeName
用法示例:
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:TTTAttributedTestString()];
[string addAttribute:kTTTBackgroundFillColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [string length])];
如何为 iOS 中的字符串添加背景颜色和圆角?
喜欢下面这张图:
NSAttributedstring
无法做到。那么,我应该使用 CoreText
吗?我找到了 this answer 但仍然不知道该怎么做。
字符串只是一种文本格式的数据,它不是可视化的。你需要标签,那里有标签。然后将您的字符串设置为该标签。
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
上面的代码创建了一个标签并设置了实现它所需的一切,如图中所示。现在您需要将此标签添加到您的视图中,或者您可以将这些属性设置为您获得的现有标签。
编辑:
如果要使文本视图中的单个文本具有彩色,可以使用 TTTAttributedLabel 并为单个文本片段设置带背景的属性文本。
您可以找到 TTTAttributedLabel here。
圆角半径: kTTTBackgroundCornerRadiusAttributeName
背景颜色: kTTTBackgroundFillColorAttributeName
用法示例:
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:TTTAttributedTestString()];
[string addAttribute:kTTTBackgroundFillColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(0, [string length])];