Start editing first column of NSBrowser

153 Views Asked by At

AppKit's NSBrowser appears to have a bug where the method */ - (void)editItemAtIndexPath:(NSIndexPath *)indexPath withEvent:(NSEvent *)theEvent select:(BOOL)select doesn't work for the first column in the browser. If indexPath is pointing to an item in the first column, nothing happens. There's another evidence to at http://www.cocoabuilder.com/archive/cocoa/327335-nsbrowser-edititematindexpath-withevent-select.html.

I've been working on a workaround for that bug. See my answer for the code.

1

There are 1 best solutions below

0
On

The solution I found is to simulate keypresses of the return key, which enters edit mode for a cell, after the cell was selected. Selecting the correct item is left exercise to the reader. Frankly, if you hit the problem above, you've probably already selected the item before.

I only simulate the key press in case where I want to edit the first column, though it'll probably work in other columns as well, but for them I prefer to use the real API, i.e. editItemAtIndexPath:withEvent:select:.

So first I check the indexPath's length to see if it's equal to 1. If it is, the following code simulates the press and release of the return key. self is an NSViewController, so you might need to adjust based on where this code is called from:

NSInteger windowNumber = [[self.view window] windowNumber];
NSEvent *keyDownReturn = [NSEvent keyEventWithType:NSKeyDown location:NSZeroPoint modifierFlags:0 timestamp:GetCurrentEventTime() windowNumber:windowNumber context:[NSGraphicsContext currentContext] characters:@"\r" charactersIgnoringModifiers:@"\r" isARepeat:NO keyCode:36];
NSEvent *keyUpReturn = [NSEvent keyEventWithType:NSKeyUp location:NSZeroPoint modifierFlags:0 timestamp:GetCurrentEventTime() windowNumber:windowNumber context:[NSGraphicsContext currentContext] characters:@"\r" charactersIgnoringModifiers:@"\r" isARepeat:NO keyCode:36];
[NSApp sendEvent:keyDownReturn];
[NSApp sendEvent:keyUpReturn];

Don't forget to #import <Carbon/Carbon.h> for GetCurrentEventTime(). Took me a while to find this one.