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
.
TTTAttributedLabel did the job for me on iOS < 6.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With