【问题标题】:Objective C - Change all attributes in NSAttributedString?Objective C - 更改 NSAttributedString 中的所有属性?
【发布时间】:2011-10-10 13:55:03
【问题描述】:
[attributedString enumerateAttributesInRange:range options:NSAttributedStringEnumerationReverse usingBlock:
     ^(NSDictionary *attributes, NSRange range, BOOL *stop) {

         NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
         [mutableAttributes setObject:[NSNumber numberWithInt:1] forKey:@"NSUnderline"];
         attributes = mutableAttributes;

     }];

我正在尝试遍历所有属性并将 NSUnderline 添加到它们。调试时,似乎 NSUnderline 已添加到字典中,但是当我第二次循环时,它们被删除了。 更新 NSDictionaries 时我做错了吗?

【问题讨论】:

    标签: iphone objective-c nsdictionary nsattributedstring


    【解决方案1】:

    您正在修改字典的本地副本;属性字符串没有任何方法可以看到更改。

    C 中的指针通过值传递(因此它们指向的内容通过引用传递。)因此,当您为attributes 分配新值时,调用该块的代码不知道您对其进行了更改。更改不会传播到块范围之外。

    【讨论】:

      【解决方案2】:

      Jonathan's answer 很好地解释了为什么它不起作用。要使其工作,您需要告诉属性字符串使用这些新属性。

      [attributedString enumerateAttributesInRange:range options:NSAttributedStringEnumerationReverse usingBlock:
           ^(NSDictionary *attributes, NSRange range, BOOL *stop) {
      
               NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
               [mutableAttributes setObject:[NSNumber numberWithInt:1] forKey:@"NSUnderline"];
               [attributedString setAttributes:mutableAttributes range:range];
      
       }];
      

      更改属性字符串的属性要求它是 NSMutableAttributedString。

      还有一种更简单的方法可以做到这一点。 NSMutableAttributedString 定义了addAttribute:value:range: 方法,该方法在指定范围内设置特定属性的值,而不更改其他属性。您可以通过对该方法的简单调用来替换您的代码(仍然需要一个可变字符串)。

      [attributedString addAttribute:@"NSUnderline" value:[NSNumber numberWithInt:1] range:(NSRange){0,[attributedString length]}];
      

      【讨论】:

      • 你能看看我关于属性字符串的其他问题吗?谢谢:stackoverflow.com/questions/6783754/…
      • addAttribute:value:range: 会在相同范围内使用相同键覆盖现有值吗?还是根本不添加属性?
      • @chown 文档没有说,所以我测试了一下,确认它覆盖了现有的值。
      • 非常酷。非常感谢您帮我解决这个问题! (我会测试自己,但我的 MacBookPro 目前已经死了)。
      猜你喜欢
      • 1970-01-01
      • 2017-09-29
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 2014-08-26
      • 2013-06-11
      • 1970-01-01
      相关资源
      最近更新 更多