-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します。originalの型をに変えてNSMutableAttributedString使う

[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 に答える