[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 时做错了什么吗?
乔纳森的回答 https://stackoverflow.com/questions/6782450/objective-c-change-all-attributes-in-nsattributedstring/6782514#6782514很好地解释了为什么它不起作用。为了使其工作,您需要告诉属性字符串使用这些新属性。
[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]}];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)