如何将 NSMutableAttributedString
中的所有属性设置为空?你必须通过它们枚举并删除它们吗?
我不想创建一个新的。我正在处理 NSTextView
中的 textStorage
。设置新字符串会重置 NSTextView
中的光标位置并触发委托(delegate)。
最佳答案
您可以像这样删除所有属性:
NSMutableAttributedString *originalMutableAttributedString = //your string…
NSRange originalRange = NSMakeRange(0, originalMutableAttributedString.length);
[originalMutableAttributedString setAttributes:@{} range:originalRange];
请注意,这使用了设置属性(而不是添加)。来自文档:
These new attributes replace any attributes previously associated with the characters in
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];
}];
}];
根据文档,这是允许的:
If this method is sent to an instance of
NSMutableAttributedString
, mutation (deletion, addition, or change) is allowed.
swift 2
如果 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)
}
}
关于ios - 如何清除 NSMutableAttributedString 中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28880889/