如何将NSMutableAttributedString
中的所有属性设置为空?你是否必须通过它们进行枚举并删除它们?
我不想创建一个新的。我正在使用textStorage
中的NSTextView
。设置一个新字符串将重置NSTextView
中的光标位置并激活该委托。
答案 0 :(得分:17)
您可以删除所有这些属性:
NSMutableAttributedString *originalMutableAttributedString = //your string…
NSRange originalRange = NSMakeRange(0, originalMutableAttributedString.length);
[originalMutableAttributedString setAttributes:@{} range:originalRange];
请注意,这使用设置属性(不是添加)。来自文档:
这些新属性会替换先前与
aRange
中的字符相关联的所有属性。
如果您需要有条件地执行任何操作,您还可以枚举属性并逐个删除它们:
[originalMutableAttributedString enumerateAttributesInRange:originalRange
options:kNilOptions
usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
[attrs enumerateKeysAndObjectsUsingBlock:^(NSString *attribute, id obj, BOOL *stop) {
[originalMutableAttributedString removeAttribute:attribute range:range];
}];
}];
根据文件,这是允许的:
如果将此方法发送到
NSMutableAttributedString
的实例,则允许进行变异(删除,添加或更改)。
如果string
是可变属性字符串:
string.setAttributes([:], range: NSRange(0..<string.length))
如果你想枚举条件删除:
string.enumerateAttributesInRange(NSRange(0..<string.length), options: []) { (attributes, range, _) -> Void in
for (attribute, object) in attributes {
string.removeAttribute(attribute, range: range)
}
}
答案 1 :(得分:3)
swift 4:
我需要从可重用单元格中的textview中删除属性,如果另一个单元格正在使用text属性,则它们会从一个单元格转移到另一个单元格,因此该文本只是一个文本,而是具有前一个属性的文本细胞。 只有这对我有用,受到上面接受的答案的启发:
<强>的iOS 强>
let attr = NSMutableAttributedString(attributedString: (cell.textView?.attributedText)!)
let originalRange = NSMakeRange(0, attr.length)
attr.setAttributes([:], range: originalRange)
cell.textView?.attributedText = attr
cell.textView?.attributedText = NSMutableAttributedString(string: "", attributes: [:])
cell.textView?.text = ""
<强> MACOS 强>
textView.textStorage?.setAttributedString(NSAttributedString(string: ""))
答案 2 :(得分:1)
NSAttributedString
是不可变的,因此你对它的一个实例做不了多少。一种选择是使用string
的{{1}}属性,用它创建一个新的NSAttributedString
并应用所需的属性或制作NSMutableAttributedString
个mutableCopy
个实例并修改范围的当前属性。
答案 3 :(得分:0)
首先,它必须是一个NSMutableAttributedString,因为它具有removeAttribute方法(name:String,range:NSRange),是的,看起来你必须枚举它们并删除它们。
为什么不尝试这种方法(Swift):
let s1 = <some NSAttributedString>
var s2 = NSMutableAttriutedString(string: s1.string())
答案 4 :(得分:0)
如何在tableView cellForRowAt indexPath中删除和添加字符串的属性。 创建一个新的NSMutableAttributedString,因为它是不可变的
// strike through on text
let attributeString = NSMutableAttributedString(string: "your string")
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
let removedAttributeString = NSMutableAttributedString(string: "your string")
removedAttributeString.removeAttribute(NSAttributedString.Key.strikethroughStyle, range: NSMakeRange(0, attributeString.length))
if (item.done == true) {
// applies strike through on text
cell.textLabel?.attributedText = attributeString
} else {
// removes strike through on text
cell.textLabel?.attributedText = removedAttributeString
}