属性字符串颜色- Objective-c

Attributed string color- Objective-c

我有一个如图所示的显示器

我是从如下字符串 str 中获取的

我试过的代码

lbl1.text=newStr;
NSString *textxtra = @"Xtra";
NSString *textremove = @"Remove";

NSMutableAttributedString *attrsString = [[NSMutableAttributedString alloc] initWithAttributedString:lbl1.attributedText];

 // search for word occurrence
                    
NSRange range = [lbl1.text rangeOfString:textxtra];
NSRange range1 = [lbl1.text rangeOfString:textremove];
if (range.location != NSNotFound) {
    [attrsString addAttribute:NSForegroundColorAttributeName value:[UIColor systemGreenColor] range:range];
}
if (range1.location != NSNotFound) {
    [attrsString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range1];
}

// set attributed text
lbl1.attributedText = attrsString;

如何获取 Xtra(美国奶酪)之前和 Xtra($1) 之后的绿色字符串?

Remove(House Mayo) 之前的红色部分? 即整个字符串 American Cheese: Xtra 应该在 green color 中。 我想到在 \n 之间取字符串。 即 Xtra 之前的字符串最多 \n 和 Xtra 之后的字符串最多 \n 但无法确切地理解如何实施

任何 ideas/suggestions 都会有帮助

未测试,但这应该可以解决问题:

NSString *initialSting = @"";

NSArray *lines = [initialSting componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

NSMutableArray *attributedLines = [[NSMutableArray alloc] init];
NSDictionary *redAttributes =  @{};
NSDictionary *greenAttributes =  @{};

for (NSString *aLine in lines) 
{
    NSAttributedString *aLineAttributedString;
    //Here, you could also check, that the string is like "someString: Xtra someOtherString", because if Xtra is misplaced...
    if ([aLine containsString:@"Xtra"]) 
    {
        aLineAttributedString = [[NSAttributedString alloc] initWithString:aLine attributes:greenAttributes];
        //Here, you could also check, that the string is like "someString: Remove someOtherString", because if Remove is misplaced...
    }
    else if ([aLine containsString:@"Remove"]) 
    {
        aLineAttributedString = [[NSAttributedString alloc] initWithString:aLine attributes:redAttributes];
    } 
    else 
    {
        aLineAttributedString = [[NSAttributedString alloc] initWithString:aLine];
    }
    [attributedLines addObject:aLineAttributedString];
}

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
NSAttributedString *newLine = [[NSAttributedString alloc] initWithString:@"\n"];

if ([attributedLines count] > 0) 
{
    for (NSUInteger i = 0; i < [attributedLines count] - 1; i++) 
    {
        [attributedString appendAttributedString:attributedLines[i]];
        [attributedString appendAttributedString:newLine];
    }
    [attributedString appendAttributedString:[attributedLines lastObject]];
}

逻辑:
使用 componentsSeparatedByCharactersInSet:
为每一行获取一个 NSString 数组 创建一个 NSAttributedString 数组,每行都将被填充。
对于每一行,根据需要为其着色,然后将其添加到数组中。
最后没有componentsJoinedByString: for NSAttributedString,所以手动做一个for循环重构最后的NSAttributedString.