Objective C - 更改NSAttributedString中的所有属性? [英] Objective C - Change all attributes in NSAttributedString?

查看:158
本文介绍了Objective C - 更改NSAttributedString中的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[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时做错了吗?

I am trying to loop through all attributed and add NSUnderline to them. when debugging it seems like NSUnderline is added to the dictionary, but when i loop for the second time they are removed. Am I doing anything wrong while updating NSDictionaries?

推荐答案

Jonathan的回答很好地解释了为什么它不起作用。为了使它工作,你需要告诉属性串来使用这些新的属性。

Jonathan's answer does a good job of explaining why it doesn't work. To make it work, you need to tell the attributed string to use these new attributes.

[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。

Changing the attributes of an attributed string requires that it is a NSMutableAttributedString.

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

There is also an easier way to do this. NSMutableAttributedString defines the addAttribute:value:range: method, which sets the value of a specific attribute over the specified range, without changing other attributes. You can replace your code with a simple call to this method (still requiring a mutable string).

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

这篇关于Objective C - 更改NSAttributedString中的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆