-3

我想知道如何更改字符串中子字符串的颜色。例如,我有以下原始黑色子字符串:

NSString *original=@"Frank Megan Timmy
                    Marcus Andrea Matt
                   Jamie Lauren Marcus";

让我们假设用户做了一些事情,我想让 Marcus Andrea Matt 在原始字符串中变成红色(例如),并保持其他一切不变。

谁能告诉我如何做到这一点?

4

3 回答 3

1
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"Frank Megan Timmy Marcus Andrea Matt Jamie Lauren Marcus"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0,18)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(18,18)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(36,20)];

UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 250, 80)];
[label setLineBreakMode:NSLineBreakByWordWrapping];
[label setNumberOfLines:0];
[label setAttributedText:string];

[self.view addSubview:label];
于 2013-06-07T10:00:41.993 回答
0

用于NSMutableAttributedString执行此操作。将类型更改originalNSMutableAttributedString并使用

[original addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:yourRange];
于 2013-06-07T09:42:31.137 回答
0

请找到以下解决方案:

NSString *original=@"Frank Megan Timmy
                    Marcus Andrea Matt
                   Jamie Lauren Marcus";
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:original];
/ now we only change the color of "Frank"
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
于 2013-06-07T09:44:39.743 回答