私が抱えている問題は、TextView 内の特定のテキストの textColor を変更できるようにしたいということです。連結された文字列を使用していますが、TextView のテキストに追加する文字列が必要です。私が使いたいのはNSMutableAttributedString
のようですが、Swift でこれを使用する方法に関するリソースが見つかりません。私がこれまでに持っているものは次のようなものです:
let string = "A \(stringOne) with \(stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString
ここから、textColor を変更する必要がある単語の範囲を見つけて、それらを属性付き文字列に追加する必要があることがわかります。私が知る必要があるのは、attributedString から正しい文字列を見つけて、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 を変更するために機能します。