Search code examples
iosnsattributedstring

Color of drawInRect:withAttributes:


Is was trying to fix some warnings in an iOS app and changed the update of this:

[[self text] drawInRect:rect withFont:[UIFont systemFontOfSize:kFontSize]];
[[UIColor whiteColor] set];

to this:

[[self text] drawInRect:rect withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kFontSize]}];
[[UIColor whiteColor] set];

However now the color of the text is black... How can I fix this?


Solution

  • You need to add the color to the attributes:

    NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:kFontSize], NSForegroundColorAttributeName : [UIColor whiteColor] };
    [[self text] drawInRect:rect withAttributes:attributes];
    

    No need to set the color the old way with this approach.