我稍微擴展了斯蒂芬的回答,以適應延遲加載菜單項。我創建了一個小協議呼籲菜單,而不是建立每個單元格的時間菜單的未來:
NSPathControlExtended.h
@protocol NSPathControlExtendedDelegate <NSPathControlDelegate>
@required
- (NSMenu *)pathControl:(NSPathControl *)pathControl menuForCell:(NSPathComponentCell *)cell;
@end
@interface NSPathControlExtended : NSPathControl
@property (weak) id <NSPathControlExtendedDelegate> delegate;
@end
NSPathControlExtended.m
#import "NSPathControlExtended.h"
@implementation NSPathControlExtended
@synthesize delegate;
- (instancetype)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Drawing code here.
}
- (void)mouseDown:(NSEvent *)event {
NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
NSPathCell *cell = self.cell;
NSPathComponentCell *componentCell = [cell pathComponentCellAtPoint:point
withFrame:self.bounds
inView:self];
NSRect componentRect = [cell rectOfPathComponentCell:componentCell
withFrame:self.bounds
inView:self];
NSMenu *menu = [delegate pathControl:self menuForCell:componentCell];
if (menu.numberOfItems > 0) {
NSUInteger selectedMenuItemIndex = 0;
for (NSUInteger menuItemIndex = 0; menuItemIndex < menu.numberOfItems; menuItemIndex++) {
if ([[menu itemAtIndex:menuItemIndex] state] == NSOnState) {
selectedMenuItemIndex = menuItemIndex;
break;
}
}
NSMenuItem *selectedMenuItem = [menu itemAtIndex:selectedMenuItemIndex];
[menu popUpMenuPositioningItem:selectedMenuItem
atLocation:NSMakePoint(NSMinX(componentRect) - 17, NSMinY(componentRect) + 2)
inView:self];
}
}
- (NSMenu *)menuForEvent:(NSEvent *)event {
if (event.type != NSLeftMouseDown) {
return nil;
}
return [super menuForEvent:event];
}
@end