我使用属性字符串格式化UITextView
的单个字符串,只要单击按钮或移动选择器,它就会更新。但是,因为我使用attributedStringLine.append(attributedCharString)
attributedString
继续增长,而不是在更新UITextView
时开始新的属性字符串。
下面的代码 演示了问题的简化版本。
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
发生变化时,如何从空的attributionString开始?
对于NSMutableString
,替换或删除现有属性字符串范围内的字符似乎是唯一可用的替代方法。而且我很确定这不是Value of type 'NSMutableAttributedString' has no member 'removeAll'
答案 0 :(得分:1)
由于您使用attributedStringLine
声明了let
,因此您可以在makeText
开头删除其中的所有字符。
func makeText() {
attributedStringLine.deleteCharacters(in: NSMakeRange(0, attributedStringLine.length))
for i in 0..<myArray.count {
appendTextString(i: i)
}
}
或者您将其声明从let
更改为var
,然后在attributedStringLine = NSMutableAttributedString()
开头使用makeText
。