相关疑难解决方法(0)

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

我遇到的问题是我希望能够在TextView中更改某些文本的textColor.我使用的是串联字符串,只是希望我附加到TextView文本中的字符串.似乎我想要使用的是NSMutableAttributedString,但我没有找到任何有关如何在Swift中使用它的资源.到目前为止我所拥有的是这样的:

let string = "A \(stringOne) with \(stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)

从这里我知道我需要找到需要更改textColor的单词范围,然后将它们添加到属性字符串中.我需要知道的是如何从attributionString中找到正确的字符串,然后更改它们的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
Run Code Online (Sandbox Code Playgroud)

由于我想要更改多个字符串的textColor,我将创建一个帮助函数来处理它,但这适用于更改textColor.

ios nsmutableattributedstring swift

90
推荐指数
8
解决办法
11万
查看次数

将NSAttributedString的子字符串替换为另一个NSAttributedString

我想将a的子串(例如@"replace")替换为NSAttributedString另一个子串NSAttributedString.

我在寻找一个相当于方法NSStringstringByReplacingOccurrencesOfString:withString:NSAttributedString.

string cocoa replace foundation nsattributedstring

52
推荐指数
6
解决办法
3万
查看次数