设置 NSAttributed 字符串属性会覆盖子字符串属性

编程入门 行业动态 更新时间:2024-10-27 06:32:36
本文介绍了设置 NSAttributed 字符串属性会覆盖子字符串属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了一个可变字符串,看起来像@"testMeIn:greenColor:Different:greencolor:Colors"

I have created a mutable string which will look like @"testMeIn:greenColor:Different:greencolor:Colors"

NSMutableAttributedString *mutableText = [[NSMutableAttributedString alloc] initWithAttributedString:myString]; UIColor *foregroundColor = [UIColor blackColor]; NSString *key = NSForegroundColorAttributeName; [mutableText addAttribute:key value:foregroundColor range:NSMakeRange(0, myString.length)];

当我添加属性 foregroundColor 时,子字符串中现有的绿色被指定的黑色覆盖.虽然我可以更改代码以设置子字符串的绿色,但我想知道是否还有其他方法可以将样式应用于没有样式的字符串部分而不覆盖现有样式.

When I add Attribute foregroundColor , the existing green color in substring gets overridden by the specified black color. Though I can change the code to set the green color for substring, I would like to know is there any other way of applying styles to the part of Strings which doesn't have styles without overriding the existing styles.

推荐答案

您可以枚举字符串中的每个属性跨度,并且仅在属性尚未设置时更改属性

You can enumerate over each attribute span in the string, and only change attributes if they are not already set

NSMutableAttributedString* aString = [[NSMutableAttributedString alloc] initWithString:@"testMeIn DIFFERENT Colors"]; [aString setAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]} range:(NSRange){9,9}]; [aString enumerateAttributesInRange:(NSRange){0,aString.length} options:nil usingBlock: ^(NSDictionary* attrs, NSRange range, BOOL *stop) { //unspecific: don't change text color if ANY attributes are set if ([[attrs allKeys] count]==0) [aString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range]; //specific: don't change text color if text color attribute is already set if (![[attrs allKeys] containsObject:NSForegroundColorAttributeName]) [aString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range]; }];

更多推荐

设置 NSAttributed 字符串属性会覆盖子字符串属性

本文发布于:2023-08-01 08:48:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1266982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   属性   NSAttributed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!