Skip to content

Instantly share code, notes, and snippets.

@TomLiu
Created February 26, 2012 13:09
Show Gist options
  • Save TomLiu/1916612 to your computer and use it in GitHub Desktop.
Save TomLiu/1916612 to your computer and use it in GitHub Desktop.
Cocoa colorful label
NSTextField *timeLabel = [[NSTextField alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
[timeLabel setAutoresizingMask:NSViewMaxXMargin|NSViewMaxYMargin|NSViewWidthSizable];
[timeLabel setEditable:NO];
[timeLabel setBordered:NO];
[timeLabel setAlignment:NSLeftTextAlignment];
[timeLabel setBackgroundColor:[NSColor clearColor]];
NSString *originString = @"firstsecondthird";
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:originString];
[string addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[NSColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[NSColor blueColor] range:NSMakeRange(11,5)];
[string addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:15.0] range:NSMakeRange(0, originString.length)];
[timeLabel setAttributedStringValue:string];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment