简体   繁体   中英

iPhone, change color to each letter

It is possible to change a NSString color by letter?

For example, if you have NSString *A=@"ASDFGH";

show in UILabel ASD with red and FGH with blue.

And another question.. If I have a NSString, can I access the letter I want? For example, in NSString *A=@"ASDFGH"; how can I know what is the second letter which is S, or the third, which is D?

1) You need to either create separate UILabels for each group of characters in the string , use NSAttributedString (see this ), or you can just use CoreGraphics to render each group in a different color. The latter is probably the most efficient but also the most complex.

2) Use -[NSString characterAtIndex:] like so:

NSString *string = @"ASDFGH";
unichar char = [string characterAtIndex:1]; //the second letter
if (char == 'S') {
  //do something
}

for your second question you can use these three methods of NSString

 – substringFromIndex:
 – substringWithRange:
 – substringToIndex:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM