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?
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.
Sorry for late answer. Below code works great for me. I am posting this so that it can be helpful to someone.
UIFont *font1 = [UIFont fontWithName:kMyriadProSemiBold size:15];
NSDictionary *arialDict = [NSDictionary dictionaryWithObject: font1 forKey:NSFontAttributeName];
NSMutableAttributedString *aAttrString1 = [[NSMutableAttributedString alloc] initWithString:@"My" attributes: arialDict];
UIFont *font2 = [UIFont fontWithName:kMyriadProRegular size:15];
NSDictionary *arialDict2 = [NSDictionary dictionaryWithObject: font2 forKey:NSFontAttributeName];
NSMutableAttributedString *aAttrString2 = [[NSMutableAttributedString alloc] initWithString:@"Profile" attributes: arialDict2];
[aAttrString1 appendAttributedString:aAttrString2];
myProfileLabel.attributedText = aAttrString1;
Please notice that My is semibold and profile is regular. I have used MyRiad font. Thanks
Use two UILabel IBOutlets, each with a different format (font/color/etc), as you desire.. Move the second one over the first based on where the first one's text ends. You can get that via sizeWithFont:forWidth:lineBreakMode:
Alternatively, you can subclass UILabel, and draw the text yourself in drawRect. If you do it this way, just add an instance variable to tell you how much of the string to draw in one format, and draw the rest in another.
Update: Please see @Akshay's response below. As of iOS6 UILabel's can contain NSMutableAttributedString. When I wrote this, this was not available.
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