Drawing colored text in UIView's -drawRect: method

RobertJoseph picture RobertJoseph · Dec 15, 2012 · Viewed 17.4k times · Source

I am trying to draw colored text in my UIView subclass. Right now I am using the Single View app template (for testing). There are no modifications except the drawRect: method.

The text is drawn but it is always black no matter what I set the color to.

- (void)drawRect:(CGRect)rect
{
    UIFont* font = [UIFont fontWithName:@"Arial" size:72];
    UIColor* textColor = [UIColor redColor];
    NSDictionary* stringAttrs = @{ UITextAttributeFont : font, UITextAttributeTextColor : textColor };

    NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:@"Hello" attributes:stringAttrs];

    [attrStr drawAtPoint:CGPointMake(10.f, 10.f)];
}

I've also tried [[UIColor redColor] set] to no avail.

Answer:

NSDictionary* stringAttrs = @{ NSFontAttributeName : font, NSForegroundColorAttributeName : textColor };

Answer

Levi picture Levi · Dec 15, 2012

Instead of UITextAttributeTextColor you should use NSForegroundColorAttributeName. Hope this helps!