Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mavericks Style Tagging

I'm quite new to cocoa and I'm trying to find out how I can create something similar to the new tagging UI in Mavericks:

enter image description here

I assume, I'll have to overwrite NSTokenFieldCell to get the coloured dots or an icon on the tags. But how does this popup list work?

Thanks for your help!

like image 644
Zap Avatar asked Nov 20 '13 09:11

Zap


1 Answers

Sadly, you'll have to roll your own. Almost all of the drawing taking place in NSTokenFieldCell is private, so adding any kind of ornamental elements would have to be done by you. If I remember correctly, NSTokenFieldCell uses an NSTokenTextView instead of the window's standard field editor. I'm not sure what's different about it, but I think it's mostly to deal with the specialized nature of "tokenizing" attributed strings. I think they just use NSAttachmentCell objects for the graphical tokens, and when the cell receives a -mouseDown: event, they show the menu.

The menu part would actually be pretty easy because you can add images to menu items like so:

NSMenuItem *redItem = [[NSMenuItem alloc] initWithTitle:@"Red"
                                                 action:@selector(chooseColorMenuItem:)
                                          keyEquivalent:@""];

// You could add an image from your app's Resources folder:
NSImage *redSwatchImage = [NSImage imageNamed:@"red-menu-item-swatch"];

// ----- or -----

// You could dynamically draw a color swatch and use that as its image:
NSImage *redSwatchImage = [NSImage imageWithSize:NSMakeSize(16.0, 16.0) 
                                         flipped:NO 
                                  drawingHandler:^BOOL(NSRect dstRect) {

    NSRect pathRect = NSInsetRect(dstRect, 0.5, 0.5); // Aligns border to integral values
    NSBezierPath *path = [NSBezierPath bezierPathWithOvalInRect:pathRect];
    NSColor *fillColor = [NSColor redColor];
    NSColor *strokeColor = [fillColor shadowWithLevel:0.5];

    [fillColor setFill];
    [path fill];

    [strokeColor setStroke];
    [path stroke];

    return YES;
}];

redItem.image = redImage;

With respect to the token drawing stuff, take my info with a grain of salt because Apple's documentation on this stuff is pretty lacking, so everything I'm telling you is from personal struggles, cursing, and head-banging. Anyway, I'm sorry I couldn't bring you better news, but I guess, it is what it is. Good luck.

like image 51
Ben Stock Avatar answered Nov 15 '22 04:11

Ben Stock