UILabel TEXT的两种颜色 [英] Two colors for UILabel TEXT

查看:93
本文介绍了UILabel TEXT的两种颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 UILabel的文本设置两种颜色。我尝试了 TTTRegexAttributedLabel ,但它抛出了未知类型错误。

I want to set two colors for UILabel's text. I tried TTTRegexAttributedLabel, but it is throwing unknown type error.

我也尝试过以下代码。但它在settext崩溃。

I tried following code too. But it is crashing at settext.

 NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Hello. That is a test attributed string."];
    [str addAttribute: @"Hello" value:[UIColor yellowColor] range:NSMakeRange(3,5)];
    [str addAttribute:@"That" value:[UIColor greenColor] range:NSMakeRange(10,7)];
    [str addAttribute:@"Hello" value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(20, 10)];

[syncStatusLabel setText:(NSString *)str];

有没有其他方法可以为单个UILabel文本设置多种颜色?

Is there any other way to set multiple colors for single UILabel text?

推荐答案

你可以设置文字颜色,如下图所示..

you can set text color with pattern image like bellow..

        [yourLable setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"yourImageName"]]];

并使用此波纹管代码设置不同的颜色..请查看详细配合的教程..

and also set different color with this bellow code.. please check tutorial with detail mate..

NSString *test = @"Hello. That is a test attributed string.";

 CFStringRef string =  (CFStringRef) test;
    CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
    CFAttributedStringReplaceString (attrString,CFRangeMake(0, 0), string);



    /*
     Note: we could have created CFAttributedStringRef which is non mutable, then we would have to give all its
     attributes right when we create it. We can change them if we use mutable form of CFAttributeString.
     */



    //Lets choose the colors we want to have in our string
    CGColorRef _orange=[UIColor orangeColor].CGColor;
    CGColorRef _green=[UIColor greenColor].CGColor;
    CGColorRef _red=[UIColor redColor].CGColor;
    CGColorRef _blue=[UIColor blueColor].CGColor;    




    //Lets have our string with first 20 letters as orange
    //next 20 letters as green
    //next 20 as red
    //last remaining as blue
    CFAttributedStringSetAttribute(attrString, CFRangeMake(0, 20),kCTForegroundColorAttributeName, _orange);
    CFAttributedStringSetAttribute(attrString, CFRangeMake(20, 20),kCTForegroundColorAttributeName, _green);
    CFAttributedStringSetAttribute(attrString, CFRangeMake(40, 20),kCTForegroundColorAttributeName, _red);    
    CFAttributedStringSetAttribute(attrString, CFRangeMake(60, _stringLength-61),kCTForegroundColorAttributeName, _blue);

了解更多信息,请参阅本教程....

for more information see this tutorial....

coretext-tutorial-for-ios -part

我希望这能帮到你...

i hope this help you...

这篇关于UILabel TEXT的两种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆