ios - 无法为多个单词提供单独的颜色
问题描述
我有一个特定的句子。我必须给那句话中的四个单词涂上黑色。
这就是我尝试过的方式......
在viewDidLoad
,
rangeArray = ["Knowledge","Events","Community","Offers"]
for text in rangeArray {
let range = (bottomTextLabel.text! as NSString).range(of: text)
let attribute = NSMutableAttributedString.init(string: bottomTextLabel.text!)
attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black , range: range)
self.bottomTextLabel.attributedText = attribute
}
但是使用此代码,我只得到黑色的“优惠”一词,而不是所有 4 个单词都为黑色。我究竟做错了什么...?
解决方案
在您的代码中,您正在self.bottomTextLabel.attributedText
为每次运行更新for loop
.
而不是你必须
NSMutableAttributedString
使用sentence
,创建一个attributes
根据您的rangeArray
和添加所有相关的- 然后最后将其设置
attrStr
为attributedText
.bottomTextLabel
这就是我想说的,
if let sentence = bottomTextLabel.text {
let rangeArray = ["Knowledge","Events","Community","Offers"]
let attrStr = NSMutableAttributedString(string: sentence)
rangeArray.forEach {
let range = (sentence as NSString).range(of: $0)
attrStr.addAttribute(.foregroundColor, value: UIColor.black, range: range)
}
self.bottomTextLabel.attributedText = attrStr
}
推荐阅读
- python-3.x - 次要情节之外的主要人物图例
- javascript - 我不知道如何创建一个按价格排序并打印成 HTML 的函数(替换)
- javascript - 使用外部配置加载 lodash 时出现 Webpack 错误
- sql - SQL查询表中所有可能的组合
- google-fit - 如何使用 REST API 为 google fit 用户检索今天的步数数据?
- r - 如何修复错误data.frame:参数暗示不同的行数:0、1?
- c# - 如何查找 1 年前最后修改的文件
- c++ - 在不需要类的情况下为数组重载 operator<<
- javascript - 如何使用带有两个变量的函数中的 JavaScript 验证 HTML 表单中的两个输入?
- javascript - “无法解析提醒错误” - django