gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 05:42:57 33 4
gpt4 key购买 nike

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

喜欢下面这张图:

enter image description here

不能用 NSAttributedstring 来做。那么,我应该使用 CoreText 吗?我找到了 this answer但仍然不知道该怎么做。

最佳答案

String只是一种文本格式的数据,它不是可视化的。你需要标签,那里有标签。然后将您的字符串设置为该标签。

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

上面的代码创建了一个标签,并设置了实现它所需的一切,如图中所示。现在您需要将此标签添加到您的 View 中,或者您可以将这些属性设置为您获得的现有标签。

编辑:

如果你想让 TextView 中的单个文本变得多彩,你可以使用 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 - 如何在 iOS 中为字符串添加背景颜色和圆角?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46069300/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com