iOS为一段文字显示不同的颜色

//需求:0次为红色
   
NSString *str = @" 您有 0 次拆红包的机会 " ;
   
NSMutableAttributedString *attributedStr = [[ NSMutableAttributedString alloc ] initWithString :str];
   
UIColor *color = [ AppUtils callColorFromHexRGB : @"5f5f5f" ];
    [attributedStr
addAttribute : NSForegroundColorAttributeName
                         
value :color
                         
range :[str rangeOfString : @" 您有 次拆红包的机会 " ]];
   
UIColor *color1 = [ UIColor redColor ];
    [attributedStr
addAttribute : NSForegroundColorAttributeName
                         
value :color1
                         
range :[str rangeOfString : @"0" ]];
   
  

//设置label的行间距
  NSMutableParagraphStyle *paregraphStyle = [[ NSMutableParagraphStyle alloc ]
                                              
init ];
    [paregraphStyle
setLineSpacing : 10.0 ];
    [attributedStr addAttribute:NSParagraphStyleAttributeName value:paregraphStyle range:NSMakeRange(0, str.length)];

    hLabel = [[ UILabel alloc ] init ];
    hLabel . attributedText = attributedStr;

你可能感兴趣的:(iOS开发)