<分区>
如果我有一个带有如下字符串的 UILabel:
func makeLabel() {
textLabel.text = "3abc 3xyz apple3 3banana 3tree pluto3"
textLabel.textColor = UIColor.black
...
}
如何仅更改“3”字符的颜色?这里还有其他问题看起来非常相似,但涉及字符串替换,而不是字符替换。
<分区>
如果我有一个带有如下字符串的 UILabel:
func makeLabel() {
textLabel.text = "3abc 3xyz apple3 3banana 3tree pluto3"
textLabel.textColor = UIColor.black
...
}
如何仅更改“3”字符的颜色?这里还有其他问题看起来非常相似,但涉及字符串替换,而不是字符替换。
最佳答案
您应该使用 textLabel.attributedText
而不是 textLabel.text
要了解 NSAttributedText 的工作原理:阅读 the documentation of NSAttributedText 或 this stack overflow answer
所以一个可能的解决方案是遍历字符串中的所有字符,如果字符是“3”则添加红色前景色
swift 3:
textLabel.attributedText = "3ab apple3 3bana".characters.reduce(NSMutableAttributedString()) {
$0.append(
NSAttributedString(
string: String($1),
attributes: [
NSForegroundColorAttributeName: $1 == "3" ? UIColor.red : .black
]
)
)
return $0
}
swift 4:
textLabel.attributedText = "3ab apple3 3bana".reduce(NSMutableAttributedString()) {
$0.append(
NSAttributedString(
string: String($1),
attributes: [
.foregroundColor: $1 == "3" ? UIColor.red : .black
]
)
)
return $0
}
我认为这不是 Color all occurrences of string in swift 的重复,因为 Strings 和 Characters 在 Swift 中是两个不同的东西!
关于ios - 如何更改 UILabel 中字符类型(而非字符串)的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45606070/