Is there a way to draw colored text using the UIKit addition for NSString on the iPhone?
views:
1625answers:
4On the desktop you can use NSAttributedString, but this isn't available on the iPhone. If you're just trying to put colored text on the screen, the easiest way is to just use a UILabel. You can manipulate the text, font and color like this:
myLabel.text = @"Your text";
myLabel.font = [UIFont boldSystemFontOfSize:16];
myLabel.textColor = [UIColor redColor];
The NSString itself has no knowledge of how it will be displayed; it's simply data. The display is handled in whatever view is presenting the text to the user. It can be a UILabel, a UITextfield, etc... These classes typically store their text in either a UILabel or a text property. The text color can usually be set by with:
aLabel = [[UILabel alloc] init];
aLabel.text = @"My String";
aLabel.textColor = [UIColor blackColor];
If by the NSString UIKit additions, you mean the category methods drawAtPoint: and drawInRect:, then all you need to do to change their drawn color is place
CGContextSetFillColorWithColor(context, textColor);
before you call drawAtPoint: or drawInRect:. The context's fill color is used as the text's color when it is drawn manually.
Brad's solution adds quite a bit of code if you do not have a context handy (for example if you are doing this in a drawRect: method).
The way to do it without CG is
[[UIColor redColor] set];
or whatever colour you want.