iPhone - UILabel containing text with multiple fonts at the same time

Tom van Zummeren picture Tom van Zummeren · Sep 13, 2009 · Viewed 72.9k times · Source

I am looking for a way to use a UILabel (or something similar) to display something like this:

Tom: Some message.

It is like how it's done in for example the Facebook app to display the "what's on your mind?" messages. Does anyone have any suggestions how to approach this?

Answer

Akshay picture Akshay · Feb 5, 2013

There is a way to set different / multiple fonts & other properties on Label using NSMutableAttributedString. Foll is my code:

 UIFont *arialFont = [UIFont fontWithName:@"arial" size:18.0];
 NSDictionary *arialDict = [NSDictionary dictionaryWithObject: arialFont forKey:NSFontAttributeName];    
 NSMutableAttributedString *aAttrString = [[NSMutableAttributedString alloc] initWithString:title attributes: arialDict];

 UIFont *VerdanaFont = [UIFont fontWithName:@"verdana" size:12.0];
 NSDictionary *verdanaDict = [NSDictionary dictionaryWithObject:VerdanaFont forKey:NSFontAttributeName];
 NSMutableAttributedString *vAttrString = [[NSMutableAttributedString alloc]initWithString: newsDate attributes:verdanaDict];    
 [vAttrString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:(NSMakeRange(0, 15))];

 [aAttrString appendAttributedString:vAttrString];


 lblText.attributedText = aAttrString;

Note that lblText is the UILabel, outlet as file owner. One can keep on appending as many NSMutableAttributedString he wants..

Also Note that I've added verdana & arial font in my project & added a plist for the same.