在UIView的-drawRect:方法中绘制彩色文本

Rob*_*eph 24 uikit nsattributedstring uicolor drawrect ios

我试图在我的UIView子类中绘制彩色文本.现在我正在使用Single View应用程序模板(用于测试).除drawRect:方法外没有任何修改.

绘制文本但无论我将颜色设置为什么,它总是黑色的.

- (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)];
}
Run Code Online (Sandbox Code Playgroud)

我也试过[[UIColor redColor] set]无济于事.

回答:

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

Lev*_*evi 22

而不是UITextAttributeTextColor你应该使用NSForegroundColorAttributeName.希望这可以帮助!

  • 那是对的.在这里你可以找到[list](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSAttributedString_AppKitAdditions/Reference/Reference.html#//apple_ref/doc/uid/ TP40004007)在属性字典中使用的所有键 (2认同)