I have a NSTextFieldCell in a column of a cell-based NSTableView. This cell should handle clicks. This works fine when no modifier keys are pressed. If I hold the shift or command keys, the table view swallows the mouseDown event in an attempt to handle row selection.
Is there a way to completely disable row selection in NSTableView?
Is there a way to have NSTableView pass through all events?
My cell subclass is derived from the LinkTextFieldCell in the TableViewLinks sample code. It implements:
- (BOOL)trackMouse:(NSEvent *)theEvent inRect:(NSRect)cellFrame ofView:(NSView *)controlView untilMouseUp:(BOOL)flag
Since I don't want row selection, my table view delegate implements:
- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)rowIndex
{
return NO;
}
- (BOOL)tableView:(NSTableView *)tableView shouldTrackCell:(NSCell *)cell forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
return YES;
}
My delegate methods are called from -[NSTableView mouseDown:]. The mouse tracking code is called when no modifier keys are pressed.
Is there a better way to fix this than subclassing NSTableView to override -[NSTableView mouseDown:]?
I have implemented a solution where I override mouseDown:. I don't really like it. But it works. Still hoping for better ideas.
- (void)mouseDown:(NSEvent *)theEvent
{
if (! [self handleMouseDown:theEvent]) {
[super mouseDown:theEvent];
}
}
- (BOOL)handleMouseDown:(NSEvent *)theEvent
{
NSInteger clickCount = [theEvent clickCount];
if (clickCount != 1) {
return NO;
}
NSPoint locationInWindow = [theEvent locationInWindow];
NSPoint locationInView = [self convertPoint:locationInWindow fromView:nil];
NSInteger clickedRow = [self rowAtPoint:locationInView];
NSInteger clickedColumn = [self columnAtPoint:locationInView];
if ((clickedRow < 0) || (clickedColumn < 0)) {
return NO;
}
if ((clickedRow >= [self numberOfRows]) || (clickedColumn >= [self numberOfColumns])) {
return NO;
}
NSArray *tableColumns = [self tableColumns];
NSTableColumn *tableColumn = [tableColumns objectAtIndex:clickedColumn];
NSCell *cell = [tableColumn dataCellForRow:clickedRow];
id <NSTableViewDelegate> delegate = [self delegate];
BOOL shouldTrackCell = NO;
if ([delegate respondsToSelector:#selector(tableView:shouldTrackCell:forTableColumn:row:)]) {
shouldTrackCell = [delegate tableView:self shouldTrackCell:cell forTableColumn:tableColumn row:clickedRow];
}
if (! shouldTrackCell) {
return NO;
}
BOOL prefersTrackingUntilMouseUp = [[cell class] prefersTrackingUntilMouseUp];
NSRect cellFrame = [self frameOfCellAtColumn:clickedColumn row:clickedRow];
return [cell trackMouse:theEvent inRect:cellFrame ofView:self untilMouseUp:prefersTrackingUntilMouseUp];
}
Related
I'm got a tableview that displays custom view cells. In viewWillAppear i've setup a long press gesture recognizer that is on the UITableView. My long press is firing and displaying the info about the cell that has been long pressed upon. However when I let go of the press the didSelectRowAtIndexPath method is firing. Is there a way to cancel the touch after the long press fires, so that the select row doesn't get triggered?
I've seen didSelectRowAtIndexPath called after long press and that question does not seem to have an adequate answer as to how to fix the problem.
#implementation ViewController
UILongPressGestureRecognizer *lpgr;
.
.
.
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
// setup long press
lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = 0.5; //seconds
lpgr.delegate = self;
lpgr.cancelsTouchesInView = true;
[self.myTableview addGestureRecognizer:lpgr];
[self.myTableview.panGestureRecognizer requireGestureRecognizerToFail:lpgr]; ...
.
.
.
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint p = [gestureRecognizer locationInView:self.myTableview];
NSIndexPath *indexPath = [self.myTableview indexPathForRowAtPoint:p];
if (indexPath == nil) {
NSLog(#"long press on table view but not on a row");
} else {
UITableViewCell *cell = [self.myTableview cellForRowAtIndexPath:indexPath];
CensusData *currentUser;
if(self.isFiltered){
currentUser = (CensusData*)[self.filteredTableData objectAtIndex:indexPath.row];
}else{
currentUser = (CensusData*)[self.dataArray objectAtIndex:indexPath.row];
}
NSLog(#"CURRENT ROW WITH LONG PRESS: %#", currentUser.friendlyName);
}
}
}
.
.
.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
While the gesture is active (begun but not ended) disable selection on the table view...
- (void)handleLongPress:(UILongPressGestureRecognizer *)gr {
if (gr.state == UIGestureRecognizerStateBegan) {
self.myTableview.allowsSelection = NO;
} else if (gr.state == UIGestureRecognizerStateEnded) {
self.myTableview.allowsSelection = YES;
}
}
No need to set the delegate, set cancelsTouches, or implement shouldRecognize... (unless you need these for something else).
EDIT This vc is a minimally complete test. It requires a storyboard with a table view wired to the outlet and the vc as the datasource and delegate...
#import "ViewController.h"
#interface ViewController () <UITableViewDataSource, UITableViewDelegate>
#property(weak,nonatomic) IBOutlet UITableView *tableView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UILongPressGestureRecognizer *gr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(handleLongPress:)];
[self.tableView addGestureRecognizer:gr];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"Row %ld", indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"selected %#", indexPath);
}
- (void)handleLongPress:(UILongPressGestureRecognizer *)gr {
if (gr.state == UIGestureRecognizerStateBegan) {
NSLog(#"long press began");
self.tableView.allowsSelection = NO;
} else if (gr.state == UIGestureRecognizerStateEnded) {
NSLog(#"long press ended");
self.tableView.allowsSelection = YES;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
You can disable tableview then only longGesture is working properly
UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(onLongPress:)];
[self.myTableview addGestureRecognizer:longPressRecognizer];
-(void)onLongPress:(UILongPressGestureRecognizer*)pGesture
{
if (pGesture.state == UIGestureRecognizerStateRecognized)
{
//Do something to tell the user!
}
if (pGesture.state == UIGestureRecognizerStateEnded)
{
CGPoint p = [pGesture locationInView:self.myTableview];
NSIndexPath *indexPath = [self.myTableview indexPathForRowAtPoint:p];
}
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
if ([touch.view isDescendantOfView:self.myTableview]) {
// Don't let selections of auto-complete entries fire the
// gesture recognizer
return NO;
}
return YES;
}
I'm working on an application that has a window with a fully sized NSOpenGLView. I'm using [view addCursorRect] and [cursor set] to show a custom cursor, but when I press any key on the keyboard, the cursor resets to the default arrow. I've also tried overriding resetCursorRects and calling invalidateCursorRects when a key is pressed, which results in a flickering cursor.
The cursor switches back to my custom cursor when I click anywhere in the view, so I suppose the keyboard presses somehow unfocus my view. Is there any way to prevent the view from becoming unfocused when I press a key?
You need to remember your cursor settings + when you need to reset call e.g refreshCursor method. Example implementation:
- (void)refreshCursor
{
NSCursor *cursor = nil;
if ([self graphic]) {
cursor = [graphic hoverCursorForPoint:[self mousePosition]];
} else if ([self group]){
cursor = [NSCursor openHandCursor];
}
[self setHoverCursor:cursor];
[self refresh];
}
- (void)updateTrackingAreas
{
[super updateTrackingAreas];
[self removeTrackingArea:[self trackingArea]];
NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:[self visibleRect]
options:NSTrackingActiveAlways|NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved
owner:self userInfo:nil];
[self setTrackingArea:area];
[self addTrackingArea:[self trackingArea]];
}
- (void)setCursorRects
{
[self discardCursorRects];
if ([self hoverCursor]) {
[self addCursorRect:[self visibleRect] cursor:[self hoverCursor]];
}
}
- (void)setHoverCursor:(NSCursor *)hoverCursor {
if (_hoverCursor != hoverCursor) {
_hoverCursor = hoverCursor;
[self setCursorRects];
}
}
- (void)resetCursorRects {
[super resetCursorRects];
[self setCursorRects];
}
- (void)mouseExited:(NSEvent *)event
{
[[NSCursor currentSystemCursor] set];
}
- (void)mouseEntered:(NSEvent *)event
{
}
- (void)mouseMoved:(NSEvent *)event
{
[self refreshCursor];
}
- (void)keyUp:(NSEvent *)event
{
[self refreshCursor];
}
//allow key events
- (BOOL)acceptsFirstResponder
{
return YES;
}
I am trying to create a custom popup menu in a tableview. As I understand it I can should be able to do so by calling the [NSPopupButtonCell setView:myView] method passing in the custom view (which is just a NSView with an NSOutlineView in it).
So I have created a NSPopupButtonCell subclass and during initialisation I call setView and pass in the custom outline view..
EDIT
In IB I have set the table columns cell to a Popup Button Cell and set
the class to my custom LookupPopupButtonCell.
I still don't get my custom view displaying but my custom classes
initialisation methods appear to be getting called.
I have since replaced this approach with using a NSTableViewDelegate method dataCellForTableColumn. Now the popup shows my custom tableView.
Still no joy in getting the NSOutlineViewDelegate methods called though.
EDIT
OK I have managed to get things working using a NSPopupButton on a view. delegate works find and table view displays things fine. Seems that using NSPopupButtonCell the delegate methods never get called.
#implementation LookupPopupButtonCell
- (id)init
{
LOG(#"init called");
self = [super init];
if (self) {
[self initialise];
}
return self;
}
- (void)initialise
{
LOG(#"initialise called");
[self setFont:[NSFont fontWithName:#"System Regular" size:11]];
[self setBordered:NO];
[self setBezeled:NO];
// Set the Task Lookup Popup Menu
NSMenu *newLookupMenu = [[NSMenu allocWithZone:[NSMenu menuZone]] initWithTitle:#"Custom"];
NSMenuItem *newItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:#"Lookup" action:nil keyEquivalent:#""];
[newItem setEnabled:YES];
TaskLookupViewController *viewController = [[TaskLookupViewController alloc] initWithNibName:#"TaskLookupViewController" bundle:nil];
[newItem setView:[viewController view]];
[newLookupMenu addItem:newItem];
[newItem release];
[self setMenu:newLookupMenu];
}
#end
#implementation TaskLookupViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Initialization code here.
[self initialise];
}
return self;
}
- (void)awakeFromNib{
LOG(#"awakeFromNib called...");
[self viewDidLoad];
}
- (void)viewDidLoad {
FLOG(#"viewDidLoad called for %#", self);
/*
FLOG(#" _outlineView is %#", _outlineView);
FLOG(#" _outlineView is %#", [_outlineView identifier]);
FLOG(#" _outlineView delegate is %#", [_outlineView delegate]);
FLOG(#" _outlineView dataSource is %#", [_outlineView dataSource]);
*/
[_outlineView setDataSource:self];
[_outlineView setDelegate:self];
[_outlineView reloadData];
[_outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
[_outlineView setNeedsDisplay];
[_outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:2] byExtendingSelection:NO];
/*
FLOG(#" _outlineView delegate is %#", [_outlineView delegate]);
FLOG(#" _outlineView dataSource is %#", [_outlineView dataSource]);
*/
//NSTableColumn *tableColumn = [[_outlineView tableColumns] objectAtIndex:0];
//LOG(#" setting bindings");
//[tableColumn bind: #"value" toObject: _treeController withKeyPath: #"arrangedObjects.displayName" options: nil];
}
- (void)initialise {
LOG(#"initialise called");
_topLevelItems = [[NSArray arrayWithObjects:#"Project", #"Tasks and Deliverables", #"Finance", nil] retain];
_childrenDictionary = [NSMutableDictionary new];
[_childrenDictionary setObject:[NSArray arrayWithObjects:#"Scope", nil] forKey:#"Project"];
//[_childrenDictionary setObject:[NSArray arrayWithObjects:#"Issues", #"Risks", nil] forKey:#"Quality"];
[_childrenDictionary setObject:[NSArray arrayWithObjects:#"WBS", #"Functions", nil] forKey:#"Tasks and Deliverables"];
[_childrenDictionary setObject:[NSArray arrayWithObjects:#"Expenses", #"Ongoing Costs", #"Timesheets", nil] forKey:#"Finance"];
//[_childrenDictionary setObject:[NSArray arrayWithObjects:#"Applications", #"Interfaces", nil] forKey:#"IT Systems"];
//[_childrenDictionary setObject:[NSArray arrayWithObjects:#"People", #"Setup", nil] forKey:#"Administration"];
}
- (NSArray *)_childrenForItem:(id)item {
LOG(#"_childrenForItem called");
NSArray *children;
if (item == nil) {
children = _topLevelItems;
} else {
children = [_childrenDictionary objectForKey:item];
}
//FLOG(#" children are %#", children);
return children;
}
#end
#implementation TaskLookupViewController (NSOutlineViewDataSource)
- (void)outlineViewSelectionDidChange:(NSNotification *)notification {
LOG(#"outlineViewSelectionDidChange: called");
if ([_outlineView selectedRow] != -1) {
NSObject *item = [_outlineView itemAtRow:[_outlineView selectedRow]];
if ([_outlineView parentForItem:item] != nil) {
// Only change things for non-root items (root items can be selected, but are ignored)
FLOG(#" selected item is %#", item);
}
}
}
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {
FLOG(#"outlineView:child:ofItem: called for item %#", item);
return [[self _childrenForItem:item] objectAtIndex:index];
}
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
LOG(#"outlineView:isItemExpandable: called");
if ([outlineView parentForItem:item] == nil) {
return YES;
} else {
return YES;
}
}
- (NSInteger) outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {
LOG(#"outlineView:numberOfChildrenOfItem: called");
FLOG(#" children count is %d", [[self _childrenForItem:item] count]);
return [[self _childrenForItem:item] count];
}
#end
#implementation TaskLookupViewController (NSOutlineViewDelegate)
- (BOOL)outlineView:(NSOutlineView *)outlineView isGroupItem:(id)item {
LOG(#"outlineView:isGroupItem: called");
return [_topLevelItems containsObject:item];
}
- (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
LOG(#"willDisplayCell called");
[cell setTitle:#"Cell Title"];
}
- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item {
LOG(#"outlineView:viewForTableColumn called");
// We just return a regular text view.
if ([_topLevelItems containsObject:item]) {
NSTextField *result = [outlineView makeViewWithIdentifier:#"HeaderTextField" owner:self];
// Uppercase the string value, but don't set anything else. NSOutlineView automatically applies attributes as necessary
NSString *value = [item uppercaseString];
[result setStringValue:value];
return result;
} else {
NSTextField *result = [outlineView makeViewWithIdentifier:#"ItemTextField" owner:self];
[result setStringValue:value];
return result;
}
}
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item;
{
LOG(#"outlineView:shouldExpandItem: called");
return YES;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldSelectItem:(id)item;
{
LOG(#"outlineView:shouldSelectItem: called");
return YES;
}
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldCollapseItem:(id)item;
{
LOG(#"outlineView:shouldCollapseItem: called");
return NO;
}
#end
#implementation TaskLookupViewController (NSTableViewDelegate)
- (NSCell *)tableView:(NSTableView *)tableView dataCellForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
LOG(#"tableView:dataCellForTableColumn:row: called");
NSString *identifier = [tableColumn identifier];
if ([identifier isEqualToString:#"task"]) {
//LOG(#" task column setting the cell");
LookupPopupButtonCell *cellView = [[LookupPopupButtonCell alloc] init];
return cellView;
}
NSTextFieldCell *cellView = [tableView makeViewWithIdentifier:#"hoursCell" owner:self];
return cellView;
}
#end
It seems you must use a VIEW based tableView to get the delegate messages. Blah, now to figure out how to bind one of them to Core Data, hopefully its not too hard !
Is there any way to reuse the same menu for each row ? I guess as long as the dataSource is not recreated each time its probably not too bad, still there could be lots of rows in this hierarchy!
I am writing a custom NSControl with custom NSCells. It is a control, so it has to respond to the mouse. I created an NSTrackingArea over my control, implemented -mouseEntered:, -mouseExited: and -mouseMoved:. (And I will have to implement -mouseUp/Down:, but I have no idea what to do in there, so for now I haven't overridden those methods yet.) In these methods I successfully determine on which cell the mouse currently is. Now I have two questions:
Is this a good approach for tracking the mouse? If not, what should I do instead?
What method should I call on my NSCell on a mouse click, when the mouse enters the cell, when the mouse leaves the cell etc? Apple's docs are not very clear about this.
So, basically: When should I call what method on my NSCell to let it respond to mouse events?
EDIT:
Rereading the docs, I think I should call NSCell's -trackMouse:inRect:ofView:untilMouseUp: and override -startTrackingAt:inView:, -continueTracking:at:inView: and -stopTracking:at:inView:mouseIsUp:. Again two questions: 1) the docs give the impression these are only called when the mouse is down. Is that correct? Then what should I do instead? 2) Where/when should I call NSCell's -trackMouse:inRect:ofView:untilMouseUp:?
I ended up implementing my own mouse tracking mechanism:
// MyControl.m:
- (void)mouseDown:(NSEvent *)theEvent {
int currentCellIndex = [self indexOfCellAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];
if (currentCellIndex < [cells count]) {
MKListCell *cell = [cells objectAtIndex:currentCellIndex];
currentCell = cell;
[currentCell mouseDown:theEvent];
}
}
- (void)mouseUp:(NSEvent *)theEvent {
int currentCellIndex = [self indexOfCellAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];
if (currentCellIndex < [cells count]) {
MKListCell *cell = [cells objectAtIndex:currentCellIndex];
[cell mouseUp:theEvent];
}
}
- (void)mouseEntered:(NSEvent *)theEvent {
int currentCellIndex = [self indexOfCellAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];
if (currentCellIndex < [cells count]) {
MKListCell *cell = [cells objectAtIndex:currentCellIndex];
currentCell = cell;
[currentCell mouseEntered:theEvent];
}
}
- (void)mouseExited:(NSEvent *)theEvent {
int currentCellIndex = [self indexOfCellAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];
if (currentCellIndex < [cells count]) {
MKListCell *cell = [cells objectAtIndex:currentCellIndex];
[cell mouseExited:theEvent];
currentCell = nil;
}
}
- (void)mouseMoved:(NSEvent *)theEvent {
int currentCellIndex = [self indexOfCellAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];
MKListCell *cell;
if (currentCellIndex < [cells count]) {
cell = [cells objectAtIndex:currentCellIndex];
}
if (currentCell != cell) {
[currentCell mouseExited:theEvent];
[cell mouseEntered:theEvent];
currentCell = cell;
}
else {
[currentCell mouseMoved:theEvent];
}
}
- (void)mouseDragged:(NSEvent *)theEvent {
int currentCellIndex = [self indexOfCellAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];
MKListCell *cell = nil;
if (currentCellIndex < [cells count]) {
cell = [cells objectAtIndex:currentCellIndex];
}
if (currentCell != cell) {
[currentCell mouseExited:theEvent];
[cell mouseEntered:theEvent];
currentCell = cell;
}
else {
[currentCell mouseMoved:theEvent];
}
}
- (int)indexOfCellAtPoint:(NSPoint)p {
int cellIndex = (self.bounds.size.height - p.y) / cellHeight;
return cellIndex;
}
And of course, in MyCell.h:
- (void)mouseDown:(NSEvent *)event;
- (void)mouseUp:(NSEvent *)event;
- (void)mouseMoved:(NSEvent *)event;
- (void)mouseEntered:(NSEvent *)event;
- (void)mouseExited:(NSEvent *)event;
With an empty implementation for those methods (so the compiler doesn't complain and I can leave the implementation of the mouse handling methods to subclasses).
From Apple's sample code and reading the docs I can see no way configuring the NSPathControl to behave similarly to e.g. the 'jump bar' in the Xcode Editor window:
I.e. have it represent a path (or other kind of hierarchy) and make each component of the path a clickable popup to navigate the hierarchy..?
Anybody having luck faking such behaviour using a NSPathControlDelegate listening to clicks and showing a menu in a temporary window?
Seems like a common design where one would even expect some OSS implementation - but no such luck yet googling for it..
I made a subclass of NSPathControl so that I can use mouseDown: to popup the context menus of the component cells at the right position. I added also a delegate to the menu to create deeper menus on demand.
- (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 = [componentCell menuForEvent:event
inRect:componentRect
ofView:self];
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];
}
I extended Stephan's answer slightly to accommodate for lazily loading the menu items. I created a small protocol to call for the menu rather than having to build the menu's ahead of time for each cell:
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