如何从NSMutableAttributedString中清除属性?

jam*_*rez 11 objective-c nsattributedstring ios swift

如何将所有属性设置NSMutableAttributedString为空?你必须通过它们进行枚举并删除它们吗?

我不想创建一个新的.我工作的textStorageNSTextView.设置新字符串会重置光标位置NSTextView并触发委托.

Aar*_*ger 19

您可以删除所有这些属性:

NSMutableAttributedString *originalMutableAttributedString = //your string…

NSRange originalRange = NSMakeRange(0, originalMutableAttributedString.length);
[originalMutableAttributedString setAttributes:@{} range:originalRange];
Run Code Online (Sandbox Code Playgroud)

请注意,这使用set Attributes(而不是add).来自文档:

这些新属性将替换先前与其中的字符关联的任何属性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];
                                                        }];
                                                    }];
Run Code Online (Sandbox Code Playgroud)

根据文档,这是允许的:

如果将此方法发送到实例NSMutableAttributedString,则允许进行变异(删除,添加或更改).


斯威夫特2

如果string是可变属性字符串:

string.setAttributes([:], range: NSRange(0..<string.length))
Run Code Online (Sandbox Code Playgroud)

如果你想枚举条件删除:

string.enumerateAttributesInRange(NSRange(0..<string.length), options: []) { (attributes, range, _) -> Void in
    for (attribute, object) in attributes {
        string.removeAttribute(attribute, range: range)
    }
}
Run Code Online (Sandbox Code Playgroud)


Cri*_*uță 5

迅速4:

我需要从可重用单元格中的文本视图中删除属性,如果另一个单元格使用文本属性,则它们会从一个单元格转移到另一个单元格,因此文本只是带有前一个单元格属性的文本。只有这对我有用,受到上面接受的答案的启发:

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 = ""
Run Code Online (Sandbox Code Playgroud)

苹果系统

textView.textStorage?.setAttributedString(NSAttributedString(string: ""))
Run Code Online (Sandbox Code Playgroud)