属性付き文字列を使用して、UITextView
の単一文字列をフォーマットしています。この文字列は、ボタンをクリックするかピッカーを移動するたびに更新されます。しかし、attributedStringLine.append(attributedCharString)
を使用しているので、UITextView
が更新されるたびに、新しい属性付き文字列を開始するのではなく、attributedString
が成長し続けます。UITextViewが変更されたときに、空のattributedStringをどのように開始するのですか?
コードの下には、のコードが簡略化されています。
NSMutableAttributedString()
は、myArray
の文字列で動作します。 UITextView
が変更されるたびに新しい文字列が処理されます。これらはarray1,
array2
とarray3
です。
import UIKit
var str = "Hello, playground"
let array1 = ["7.0", "55.55", "1.0", "9.27"]
let array2 = ["0", "10", "20", "30", "40"]
let array3 = ["A", "B", "C", "D", "E", "F"]
var myArray = [""]
let attributedStringLine = NSMutableAttributedString()
let numberOfRawStringCharacters = myArray.count
func appendTextString(i: Int){
let rangeOfCharString = (myArray[i] as NSString).range(of: myArray[i])
let attributedCharString = NSMutableAttributedString.init(string: myArray[i], attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18.0, weight: UIFontWeightLight)])
attributedCharString.addAttributes([NSForegroundColorAttributeName : UIColor.blue], range: rangeOfCharString)
attributedStringLine.append(attributedCharString)
}
func makeText() {
for i in 0..<myArray.count {
appendTextString(i: i)
}
}
var line = attributedStringLine.length
myArray.removeAll()
myArray = array1
myArray.count
makeText()
print(attributedStringLine)
line = attributedStringLine.length
myArray.removeAll()
myArray = array2
myArray.count
makeText()
attributedStringLine
line = attributedStringLine.length
myArray.removeAll()
myArray = array3
myArray.count
makeText()
attributedStringLine
line = attributedStringLine.length
UITextView
が変更されたときに空のattributedStringを使用して開始するにはどうすればよいですか?
NSMutableString
については、既存の属性付き文字列の範囲から文字を置換または削除することが唯一の選択肢です。そして、私は、これはあなたがlet
でattributedStringLine
を宣言しているので、あなたがmakeText
の開始時に、それから、すべての文字を削除することができValue of type 'NSMutableAttributedString' has no member 'removeAll'
あなたの最初の解決策は私のXcodeプロジェクトでうまくいきましたので、私の考え方からは受け入れられた答えになります。 Playgroundの属性文字列が 'array2'と' array3'のために正しくフォーマットされているように見えるのですが、 'array1'の場合は、フォーマットされていない文字列の後に中括弧で囲まれた属性書式スクリプトが続きます。 Simulatorでは、これらの数値浮動小数点文字が正しく表示されます。ありがとう。 – Greg