ios - 如何清除 NSMutableAttributedString 中的属性?

标签 ios objective-c swift nsattributedstring

如何将 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/

相关文章:

ios - 如何计算UITextView中文本的高度?

iphone - 如何获取 UI 按钮 iPhone 的 X 和 Y 位置

iphone - 添加自定义图像以在 iPhone 中启动应用程序?

objective-c - NSString 和 NSUrl 转换不正确

swift - 在数组索引上创建随机字符串

android - 可以在 Android 的 RecyclerView 中定义部分吗?

ios - 通过自动布局在 UIScrollview 中以编程方式使用 UIStackView

swift - 小于或大于 Swift switch 语句

ios - 使用 GCD 计算从后台队列加载数据的百分比

ios - SwiftUi:从 WatchKit 的详细 View 中删除 "Back"按钮