每当 UITextView 更改时,如何从空的 attributedString 开始?

How do I start with an empty attributedString whenever the UITextView changes?

我正在使用属性字符串为 UITextView 格式化单个字符串,只要单击按钮或移动选择器,该字符串就会更新。但是,因为我使用 attributedStringLine.append(attributedCharString),所以 attributedString 会继续增长,而不是在 UITextView 更新时开始一个新的属性字符串。

下面的代码演示了该问题的简化版本。

NSMutableAttributedString()myArray 中的字符串进行操作。只要 UITextView 发生变化,就会处理新字符串。这些在 array1, array2array3.

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.

开头删除所有字符
func makeText() {
    attributedStringLine.deleteCharacters(in: NSMakeRange(0, attributedStringLine.length))
    for i in 0..<myArray.count {
        appendTextString(i: i)
    }
}

或者您将其声明从 let 更改为 var,然后在 makeText 的开头使用 attributedStringLine = NSMutableAttributedString()