Swift Stringの一部の範囲に属性を追加しようとしています。 部分文字列に最初と最後の記号の範囲を見つけ、それらの間のテキストに赤を含めて色付けしました。Swift NSAttributedStringに文字列より多くの文字がありますか?
let mutableString = NSMutableAttributedString(string: text)
let str = mutableString.string
//Red symbols
var t = 0
let symbols = mutableString.string.characters.count
while t < symbols {
if str[t] == "[" {
let startIndex = t
while str[t] != "]" {
t += 1
}
t += 1
let endIndex = t
mutableString.addAttribute(
NSForegroundColorAttributeName,
value: UIColor.redColor(),
range: NSMakeRange(startIndex, endIndex - startIndex))
}
t += 1
}
しかし、文字列とNSMutableAttributedStringの範囲が等しくないことがわかりました。文字列の範囲はより短いです(このテキストはUnicodeエンコーディングではありません)。 NSAttributedStringには、基になるStringではなく範囲を見つける方法がありますか?
例:
print(mutableString.length) //550
print(mutableString.string.characters.count) //548
なぜこの違いは何ですか?
"このテキストはUnicodeエンコーディングではありません" _that_は何を意味していますか? – matt
Windows CP1251をエンコードしています –
「Windows CP1251をエンコードしています」まあ、そうではありません。文字列はUnicodeです。文字列を作成したときにWindows CP1251から変換したはずです。あなたが今持っているものは混乱の何かかもしれません。 – matt