我遇到的问题是我希望能够更改 TextView 中某些文本的 textColor。我正在使用连接字符串,并且只想要我附加到 TextView 文本中的字符串。看来我想使用的是NSMutableAttributedString
,但我没有找到任何关于如何在 Swift 中使用它的资源。我到目前为止是这样的:
let string = "A \(stringOne) with \(stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString
从这里我知道我需要找到需要更改其 textColor 的单词范围,然后将它们添加到属性字符串中。我需要知道的是如何从attributeString中找到正确的字符串,然后改变它们的textColor。
由于我的评分太低,我无法回答自己的问题,但这是我找到的答案
我通过翻译从翻译一些代码找到了自己的答案
更改 NSAttributedString 中子字符串的属性
以下是 Swift 中的实现示例:
let string = "A \(stringOne) and \(stringTwo)"
var attributedString = NSMutableAttributedString(string:string)
let stringOneRegex = NSRegularExpression(pattern: nameString, options: nil, error: nil)
let stringOneMatches = stringOneRegex.matchesInString(longString, options: nil, range: NSMakeRange(0, attributedString.length))
for stringOneMatch in stringOneMatches {
let wordRange = stringOneMatch.rangeAtIndex(0)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.nameColor(), range: wordRange)
}
textView.attributedText = attributedString
由于我想更改多个字符串的 textColor,我将创建一个辅助函数来处理此问题,但这适用于更改 textColor。