Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Display different colors and font types in a UILabel [duplicate]

I have a String Like,

NSSting *myString=@"First Second Third Fourth Fifth Sixth Seventh";

I want to display this string in single label with different font types and colors.

i.e..,

"First" string should be in Bold.

"Second" string should be in italic.

"Third" string should be in red color.

"Fourth" string should be in green color.

"Fifth" string should be in Bold Italic of System font.

"Sixth" String should be arial bold.

"Seventh" String should be arial bold of size 34.

I have gone through some of the answers in stackoverflow, but i didn't get any clarity in those answers..

Can any one provide some guidelines.

Thanks in Advance.

Solution : Firstly manipulate NSAttributedString according to your requirement.

using NSAttributedString u can do it in iOS 6 UILabel has attributedString property.

Below ios 6.0 use TTAtributeLabel or any third party attributedLabel for displaying attributedString.

like image 843
Ashok Avatar asked May 08 '13 11:05

Ashok


2 Answers

TTTAttributedLabel did the job for me on iOS < 6.

like image 26
Michał Ciuba Avatar answered Nov 15 '22 08:11

Michał Ciuba


Use this code for set different color to different word..

NSString *test = @"First Second Third Fourth Fifth Sixth Seventh";

 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);

Also you can set Color with Image like bellow..

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

See My Another Answer From This Link

like image 154
Paras Joshi Avatar answered Nov 15 '22 06:11

Paras Joshi