我遇到的问题是我希望能够更改 TextView 中某些文本的 textColor。我正在使用一个连接的字符串,并且只想要我附加到 TextView 文本中的字符串。看起来我想使用的是 NSMutableAttributedString
,但我没有找到任何关于如何在 Swift 中使用它的资源。到目前为止,我所拥有的是这样的:
let string = "A \(stringOne) with \(stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString
从这里我知道我需要找到需要更改其 textColor 的单词范围,然后将它们添加到属性字符串中。我需要知道的是如何从 attributedString 中找到正确的字符串,然后更改它们的 textColor。
由于我的评分太低,我无法回答我自己的问题,但这是我找到的答案
我从翻译一些代码中找到了自己的答案
Change attributes of substrings in a 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。
let mainString = "Hello World"
let stringToColor = "World"
SWIFT 5
let range = (mainString as NSString).range(of: stringToColor)
let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString
SWIFT 4.2
let range = (mainString as NSString).range(of: stringToColor)
let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString
Tôi là một lập trình viên xuất sắc, rất giỏi!