ios - 将具有不同样式的文本添加到现有标签
问题描述
我有一个带有文本的标签,想在运行时添加更多测试,但我想为这个添加的文本添加不同的样式。有没有办法做到这一点?
这是代码
label.text = (label.text ?? "") + " \n \(userName)"
如何在userName
不更改标签样式的情况下添加样式?
解决方案
为此,您需要使用 NSMutableAttributedString、NSAttributedString 并使用 label.attributedText,如何?
这样做:
let userName = "StackOverflow"
let prefixText = NSAttributedString(string: "this is normal ")
let font = UIFont.systemFont(ofSize: 40)
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: UIColor.blue
]
let userNameWithStyle = NSAttributedString(string: userName, attributes: attributes)
let finalString = NSMutableAttributedString(attributedString: prefixText)
finalString.append(userNameWithStyle)
self.label.attributedText = finalString
推荐阅读
- javascript - 如何在javascript中计算数组中的每个元素数
- windows - 如何使用 AutoHotkey 激活后台进程?
- python - Python:Django:如何使用 python 脚本运行 django 应用程序
- amazon-web-services - AWS 密钥对替换
- html - 使用 css 更改部分 SVG 颜色
- hash - 我什么时候应该选择 murmur 或 cityhash 而不是 ie。沙256?
- shopify - 单击shopify中的增量和减量按钮时如何更新购物车页面上的小计
- google-chrome - 向响应标头添加多个值的方法
- amazon-web-services - cloudformation 多重 if 条件
- python - 如何使用存档获取网页的所有损坏链接?