gpt4 book ai didi

ios - 在 Swift 中使用 NSMutableAttributedString 更改特定文本的颜色

转载 作者:行者123 更新时间:2023-11-28 08:32:33 24 4
gpt4 key购买 nike

我遇到的问题是我希望能够更改 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

关于ios - 在 Swift 中使用 NSMutableAttributedString 更改特定文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38588990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com