How do you use NSAttributedString?

后端 未结 15 965
佛祖请我去吃肉
佛祖请我去吃肉 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 04:50

    This solution will work for any length

    NSString *strFirst = @"Anylengthtext";
    NSString *strSecond = @"Anylengthtext";
    NSString *strThird = @"Anylengthtext";
    
    NSString *strComplete = [NSString stringWithFormat:@"%@ %@ %@",strFirst,strSecond,strThird];
    
    NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:strComplete];
    
    [attributedString addAttribute:NSForegroundColorAttributeName
                  value:[UIColor redColor]
                  range:[strComplete rangeOfString:strFirst]];
    
    [attributedString addAttribute:NSForegroundColorAttributeName
                  value:[UIColor yellowColor]
                  range:[strComplete rangeOfString:strSecond]];
    
    [attributedString addAttribute:NSForegroundColorAttributeName
                  value:[UIColor blueColor]
                  range:[strComplete rangeOfString:strThird]];
    
    
    self.lblName.attributedText = attributedString;
    

提交回复
热议问题