How do you use NSAttributedString?

后端 未结 15 1154
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 04:19

Multiple colours in an NSString or NSMutableStrings are not possible. So I\'ve heard a little about the NSAttributedString which was introduced wit

15条回答
  •  借酒劲吻你
    2020-11-22 05:09

    When building attributed strings, I prefer to use the mutable subclass, just to keep things cleaner.

    That being said, here's how you create a tri-color attributed string:

    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
    

    typed in a browser. caveat implementor

    Obviously you're not going to hard-code in the ranges like this. Perhaps instead you could do something like:

    NSDictionary * wordToColorMapping = ....;  //an NSDictionary of NSString => UIColor pairs
    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@""];
    for (NSString * word in wordToColorMapping) {
      UIColor * color = [wordToColorMapping objectForKey:word];
      NSDictionary * attributes = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
      NSAttributedString * subString = [[NSAttributedString alloc] initWithString:word attributes:attributes];
      [string appendAttributedString:subString];
      [subString release];
    }
    
    //display string
    

提交回复
热议问题