Respond to mouse events in text field in view-based table view - cocoa

I have text fields inside a custom view inside an NSOutlineView. Editing one of these cells requires a single click, a pause, and another single click. The first single click selects the table view row, and the second single click draws the cursor in the field. Double-clicking the cell, which lets you edit in a cell-based table view, only selects the row.
The behavior I want: one click to change the selection and edit.
What do I need to override to obtain this behavior?
I've read some other posts:
The NSTextField flyweight pattern wouldn't seem to apply to view-based table views, where the cell views are all instantiated from nibs.
I tried subclassing NSTextField like this solution describes, but my overridden mouseDown method is not called. Overridden awakeFromNib and viewWillDraw (mentioned in this post) are called. Of course mouseDown is called if I put the text field somewhere outside a table view.
By comparison, a NSSegmentedControl in my cell view changes its value without first selecting the row.
Here's the working solution adapted from the accepted response:
In outline view subclass:
-(void)mouseDown:(NSEvent *)theEvent {
[super mouseDown:theEvent];
// Forward the click to the row's cell view
NSPoint selfPoint = [self convertPoint:theEvent.locationInWindow fromView:nil];
NSInteger row = [self rowAtPoint:selfPoint];
if (row>=0) [(CellViewSubclass *)[self viewAtColumn:0 row:row makeIfNecessary:NO]
mouseDownForTextFields:theEvent];
}
In table cell view subclass:
// Respond to clicks within text fields only, because other clicks will be duplicates of events passed to mouseDown
- (void)mouseDownForTextFields:(NSEvent *)theEvent {
// If shift or command are being held, we're selecting rows, so ignore
if ((NSCommandKeyMask | NSShiftKeyMask) & [theEvent modifierFlags]) return;
NSPoint selfPoint = [self convertPoint:theEvent.locationInWindow fromView:nil];
for (NSView *subview in [self subviews])
if ([subview isKindOfClass:[NSTextField class]])
if (NSPointInRect(selfPoint, [subview frame]))
[[self window] makeFirstResponder:subview];
}

Had the same problem. After much struggle, it magically worked when I selected None as against the default Regular (other option is Source List) for the Highlight option of the table view in IB!
Another option is the solution at https://stackoverflow.com/a/13579469/804616, which appears to be more specific but a little hacky compared to this.

I'll try to return the favor... Subclass NSOutlineView and override -mouseDown: like so:
- (void)mouseDown:(NSEvent *)theEvent {
[super mouseDown:theEvent];
// Only take effect for double clicks; remove to allow for single clicks
if (theEvent.clickCount < 2) {
return;
}
// Get the row on which the user clicked
NSPoint localPoint = [self convertPoint:theEvent.locationInWindow
fromView:nil];
NSInteger row = [self rowAtPoint:localPoint];
// If the user didn't click on a row, we're done
if (row < 0) {
return;
}
// Get the view clicked on
NSTableCellView *view = [self viewAtColumn:0 row:row makeIfNecessary:NO];
// If the field can be edited, pop the editor into edit mode
if (view.textField.isEditable) {
[[view window] makeFirstResponder:view.textField];
}
}

You really want to override validateProposedFirstResponder and allow a particular first responder to be made (or not) depending on your logic. The implementation in NSTableView is (sort of) like this (I'm re-writing it to be pseudo code):
- (BOOL)validateProposedFirstResponder:(NSResponder *)responder forEvent:(NSEvent *)event {
// We want to not do anything for the following conditions:
// 1. We aren't view based (sometimes people have subviews in tables when they aren't view based)
// 2. The responder to valididate is ourselves (we send this up the chain, in case we are in another tableview)
// 3. We don't have a selection highlight style; in that case, we just let things go through, since the user can't appear to select anything anyways.
if (!isViewBased || responder == self || [self selectionHighlightStyle] == NSTableViewSelectionHighlightStyleNone) {
return [super validateProposedFirstResponder:responder forEvent:event];
}
if (![responder isKindOfClass:[NSControl class]]) {
// Let any non-control become first responder whenever it wants
result = YES;
// Exclude NSTableCellView.
if ([responder isKindOfClass:[NSTableCellView class]]) {
result = NO;
}
} else if ([responder isKindOfClass:[NSButton class]]) {
// Let all buttons go through; this would be caught later on in our hit testing, but we also do it here to make it cleaner and easier to read what we want. We want buttons to track at anytime without any restrictions. They are always valid to become the first responder. Text editing isn't.
result = YES;
} else if (event == nil) {
// If we don't have any event, then we will consider it valid only if it is already the first responder
NSResponder *currentResponder = self.window.firstResponder;
if (currentResponder != nil && [currentResponder isKindOfClass:[NSView class]] && [(NSView *)currentResponder isDescendantOf:(NSView *)responder]) {
result = YES;
}
} else {
if ([event type] == NSEventTypeLeftMouseDown || [event type] == NSEventTypeRightMouseDown) {
// If it was a double click, and we have a double action, then send that to the table
if ([self doubleAction] != NULL && [event clickCount] > 1) {
[cancel the first responder delay];
}
...
The code here checks to see if the text field
cell had text hit. If it did, it attempts to edit it on a delay.
Editing is simply making that NSTextField the first responder.
...
}

I wrote the following to support the case for when you have a more complex NSTableViewCell with multiple text fields or where the text field doesn't occupy the whole cell. There a trick in here for flipping y values because when you switch between the NSOutlineView or NSTableView and it's NSTableCellViews the coordinate system gets flipped.
- (void)mouseDown:(NSEvent *)theEvent
{
[super mouseDown: theEvent];
NSPoint thePoint = [self.window.contentView convertPoint: theEvent.locationInWindow
toView: self];
NSInteger row = [self rowAtPoint: thePoint];
if (row != -1) {
NSView *view = [self viewAtColumn: 0
row: row
makeIfNecessary: NO];
thePoint = [view convertPoint: thePoint
fromView: self];
if ([view isFlipped] != [self isFlipped])
thePoint.y = RectGetHeight(view.bounds) - thePoint.y;
view = [view hitTest: thePoint];
if ([view isKindOfClass: [NSTextField class]]) {
NSTextField *textField = (NSTextField *)view;
if (textField.isEnabled && textField.window.firstResponder != textField)
dispatch_async(dispatch_get_main_queue(), ^{
[textField selectText: nil];
});
}
}
}

Just want to point out that if all that you want is editing only (i.e. in a table without selection), overriding -hitTest: seems to be simpler and a more Cocoa-like:
- (NSView *)hitTest:(NSPoint)aPoint
{
NSInteger column = [self columnAtPoint: aPoint];
NSInteger row = [self rowAtPoint: aPoint];
// Give cell view a chance to override table hit testing
if (row != -1 && column != -1) {
NSView *cell = [self viewAtColumn:column row:row makeIfNecessary:NO];
// Use cell frame, since convertPoint: doesn't always seem to work.
NSRect frame = [self frameOfCellAtColumn:column row:row];
NSView *hit = [cell hitTest: NSMakePoint(aPoint.x + frame.origin.x, aPoint.y + frame.origin.y)];
if (hit)
return hit;
}
// Default implementation
return [super hitTest: aPoint];
}

Here is a swift 4.2 version of #Dov answer:
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
if (event.clickCount < 2) {
return;
}
// Get the row on which the user clicked
let localPoint = self.convert(event.locationInWindow, from: nil)
let row = self.row(at: localPoint)
// If the user didn't click on a row, we're done
if (row < 0) {
return
}
DispatchQueue.main.async {[weak self] in
guard let self = self else {return}
// Get the view clicked on
if let clickedCell = self.view(atColumn: 0, row: row, makeIfNecessary: false) as? YourOutlineViewCellClass{
let pointInCell = clickedCell.convert(localPoint, from: self)
if (clickedCell.txtField.isEditable && clickedCell.txtField.hitTest(pointInCell) != nil){
clickedCell.window?.makeFirstResponder(clickedCell.txtField)
}
}
}
}

Related

Accessibility: ScrollView to auto scroll to the view which are not visible on hitting "TAB"

Could someone let me know how can I automatically scroll the scrollView when a keyboard-only user tries to navigate between different UI Element in the ScrollView using ‘Tab’ key? When I hit "TAB" key the focus is shifted to different UI element present in the scrollView but it doesn't scroll if the UI Element is not present in the Visible Content View. How can this be achieved. Help would be appreciated. Thanks.
Solution A: Create a subclass of NSWindow and override makeFirstResponder:. makeFirstResponder is called when the first responder changes.
- (BOOL)makeFirstResponder:(NSResponder *)responder {
BOOL madeFirstResponder = [super makeFirstResponder:responder];
if (madeFirstResponder) {
id view = [self firstResponder];
// check if the new first responder is a field editor
if (view && [view isKindOfClass:[NSTextView class]] && [view isFieldEditor])
view = [view delegate]; // the control, usually a NSTextField
if (view && [view isKindOfClass:[NSControl class]] && [view enclosingScrollView]) {
NSRect rect = [view bounds];
rect = NSInsetRect(rect, -10.0, -10.0); // add a margin
[view scrollRectToVisible:rect];
}
}
return madeFirstResponder;
}
Solution B: Create a subclass of NSTextField and other controls and override becomeFirstResponder.
- (BOOL)becomeFirstResponder {
BOOL becameFirstResponder = [super becomeFirstResponder];
if (becameFirstResponder) {
if ([self enclosingScrollView]) {
NSRect rect = [self bounds];
rect = NSInsetRect(rect, -10.0, -10.0); // add a margin
[self scrollRectToVisible:rect];
}
}
return becameFirstResponder;
}

NSTableView reloadData method causes NSProgressIndicator in all rows to update and flicker

Note: I have searched Stack Overflow for similar problems, and none of the questions I found seem to address this particular problem.
I've written a small sample app (complete Xcode project with source code available here: http://jollyroger.kicks-ass.org/stackoverflow/FlickeringTableView.zip) that plays all of the sounds in /System/Library/Sounds/ sequentially and displays the sounds in a window as they are played to show the issue I am seeing. The window in MainMenu.xib has a single-column NSTableView with one row defined as a cell template with three items in it:
an NSTextField to hold the sound name
another NSTextField to hold the sound details
a NSProgressIndicator to show play progress while the sound is playing
I have subclassed NSTableCellView (SoundsTableCellView.h) to define each of the items in the cell view so that I can access and set them when the time arises.
I have defined a MySound class that encapsulates properties and methods needed to handle the playing of sound files via AVAudioPlayer APIs. This class defines a MySoundDelegate protocol to allow the app delegate to receive events whenever sounds start or finish playing.
The application delegate adheres to the NSTableViewDelegate and NSTableViewDataSource protocols to allow it to store the table data as an array of MySound objects and update the table with relevant information when needed. It also adheres to the MySoundDelegate protocol to receive events when sounds start or finish playing. The delegate also has an NSTimer task that periodically calls a refreshWindow method to update the progress indicator for the currently playing sound.
The app delegate's refreshWindow method displays and resizes the window if needed based on the number of sounds in the list, and updates the stored reference to the associated NSProgressIndicator for the sound that is playing.
The app delegate's tableView: viewForTableColumn (NSTableViewDelegate protocol) method gets called to populate the table cells. In it, I use Apple's standard "Populating a Table View Programmatically" advice to:
check the table column identifier to ensure it matches the
identifier (sound column) I set in Interface Builder (Xcode) for the table column,
get the corresponding table cell with identifier (sound cell) by calling thisTableView makeViewWithIdentifier,
use the incoming row parameter to locate the matching array element
of the data source (app delegate sounds array), then
set the string values of NSTextFields and set the maxValue and doubleValue of the NSProgressIndicator in the cell to corresponding details of the associated sound object,
store a reference to the associated NSProgressIndicator control in the associated sound object for later updating
Here's the viewForTableColumn method:
- (NSView *)tableView:(NSTableView *)thisTableView viewForTableColumn:(NSTableColumn *)thisTableColumn row:(NSInteger)thisRow
{
SoundsTableCellView *cellView = nil;
// get the table column identifier
NSString *columnID = [thisTableColumn identifier];
if ([columnID isEqualToString:#"sound column"])
{
// get the sound corresponding to the specified row (sounds array index)
MySound *sound = [sounds objectAtIndex:thisRow];
// get an existing cell from IB with our hard-coded identifier
cellView = [thisTableView makeViewWithIdentifier:#"sound cell" owner:self];
// display sound name
[cellView.soundName setStringValue:[sound name]];
[cellView.soundName setLineBreakMode:NSLineBreakByTruncatingMiddle];
// display sound details (source URL)
NSString *details = [NSString stringWithFormat:#"%#", [sound sourceURL]];
[cellView.soundDetails setStringValue:details];
[cellView.soundDetails setLineBreakMode:NSLineBreakByTruncatingMiddle];
// update progress indicators
switch ([sound state])
{
case kMySoundStateQueued:
break;
case kMySoundStateReadyToPlay:
break;
case kMySoundStatePlaying:
if (sound.playProgress == nil)
{
sound.playProgress = cellView.playProgress;
}
NSTimeInterval duration = [sound duration];
NSTimeInterval position = [sound position];
NSLog(#"row %ld: %# (%f / %f)", (long)thisRow, [sound name], position, duration);
NSLog(#" %#: %#", [sound name], sound.playProgress);
[cellView.playProgress setMaxValue:duration];
[cellView.playProgress setDoubleValue:position];
break;
case kMySoundStatePaused:
break;
case kMySoundStateFinishedPlaying:
break;
default:
break;
}
}
return cellView;
}
And here's the refreshWindow method:
- (void) refreshWindow
{
if ([sounds count] > 0)
{
// show window if needed
if ([window isVisible] == false)
{
[window makeKeyAndOrderFront:self];
}
// resize window to fit all sounds in the list if needed
NSRect frame = [self.window frame];
int screenHeight = self.window.screen.frame.size.height;
long maxRows = ((screenHeight - 22) / 82) - 1;
long displayedRows = ([sounds count] > maxRows ? maxRows : [sounds count]);
long actualHeight = frame.size.height;
long desiredHeight = 22 + (82 * displayedRows);
long delta = desiredHeight - actualHeight;
if (delta != 0)
{
frame.size.height += delta;
frame.origin.y -= delta;
[self.window setFrame:frame display:YES];
}
// update play position of progress indicator for all sounds in the list
for (MySound *nextSound in sounds)
{
switch ([nextSound state])
{
case kMySoundStatePlaying:
if (nextSound.playProgress != nil)
{
[nextSound.playProgress setDoubleValue:[nextSound position]];
NSLog(#" %#: %# position: %f", [nextSound name], nextSound.playProgress, [nextSound position]);
}
break;
case kMySoundStateQueued:
case kMySoundStateReadyToPlay:
case kMySoundStatePaused:
case kMySoundStateFinishedPlaying:
default:
break;
}
}
}
else
{
// hide window
if ([window isVisible])
{
[window orderOut:self];
}
}
// reload window table view
[tableView reloadData];
}
During init, the application delegate scans the /System/Library/Sounds/ folder to get a list of AIFF sound files in that folder, and creates a sounds array holding sound objects for each of the sounds in that folder. The applicationDidFinishLaunching method then starts playing the first sound in the list sequentially.
The problem (which you can see by running the sample project) is that rather than only updating the top table row for the sound that is currently playing, the progress indicators in all of the following rows seem to update and flicker as well. The way it displays is somewhat inconsistent (sometimes they all flicker, and sometimes they are all blank as expected); but when they do update and flicker the progress indicators do seem to roughly correspond to the sound that is currently playing. So I am pretty sure the issue must be somehow related to the way I am updating the table; I'm just not sure where the problem is or how to solve it.
Here's a screen shot of what the window looks like to give you an idea:
Table View Screen Shot
Any ideas or guidance would be greatly appreciated!
Here's what I changed.
tableView:viewForTableColumn:row: returns "a view to display the specified row and column". The value of the progress bar is always set.
- (NSView *)tableView:(NSTableView *)thisTableView viewForTableColumn:(NSTableColumn *)thisTableColumn row:(NSInteger)thisRow
{
SoundsTableCellView *cellView = nil;
// get the table column identifier
NSString *columnID = [thisTableColumn identifier];
if ([columnID isEqualToString:#"sound column"])
{
// get the sound corresponding to the specified row (sounds array index)
MySound *sound = [sounds objectAtIndex:thisRow];
// get an existing cell from IB with our hard-coded identifier
cellView = [thisTableView makeViewWithIdentifier:#"sound cell" owner:self];
// display sound name
[cellView.soundName setStringValue:[sound name]];
// display sound details (source URL)
NSString *details = [NSString stringWithFormat:#"%#", [sound sourceURL]];
[cellView.soundDetails setStringValue:details];
// update progress indicators
// [cellView.playProgress setUsesThreadedAnimation:NO];
NSTimeInterval duration = [sound duration];
NSTimeInterval position = [sound position];
[cellView.playProgress setMaxValue:duration];
[cellView.playProgress setDoubleValue:position];
}
// end updates
// [thisTableView endUpdates];
return cellView;
}
refreshWindow is split into refreshProgress and refreshWindow. refreshProgress refreshes the row of the playing sound and is called on a timer.
- (void)refreshProgress
{
if ([sounds count] > 0)
{
[sounds enumerateObjectsUsingBlock:^(MySound *nextSound, NSUInteger rowNr, BOOL *stop)
{
switch ([nextSound state])
{
case kMySoundStatePlaying:
// refresh row
[tableView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:rowNr]
columnIndexes:[NSIndexSet indexSetWithIndex:0]];
break;
case kMySoundStateQueued:
case kMySoundStateReadyToPlay:
case kMySoundStatePaused:
case kMySoundStateFinishedPlaying:
default:
break;
}
}];
}
}
refreshWindow refreshes the size and visibility of the window and is called when the number of sounds changes.
- (void) refreshWindow
{
if ([sounds count] > 0)
{
// show window if needed
if ([window isVisible] == false)
{
[window makeKeyAndOrderFront:self];
}
// resize window to fit all sounds in the list if needed
... calculate new window frame
}
else
{
// hide window
if ([window isVisible])
{
[window orderOut:self];
}
}
}
When a sound is removed, the row is also removed so the other rows still display the same sound and don't need an update.
- (void) soundFinishedPlaying:(MySound *)sound encounteredError:(NSError *)error
{
if (error != NULL)
{
// display an error dialog box to the user
[NSApp presentError:error];
}
else
{
// remove sound from array
NSLog(#"deleting: [%#|%#]", [sound truncatedID], [sound name]);
NSUInteger index = [sounds indexOfObject:sound];
[sounds removeObject:sound];
[tableView removeRowsAtIndexes:[NSIndexSet indexSetWithIndex:index] withAnimation:NSTableViewAnimationEffectNone];
}
// refresh window
[self refreshWindow];
// play the next sound in the queue
[self play];
}
[tableView reloadData] isn't called. sound.playProgress isn't used.

Getting duplicate header button cell in NSTableView when using NSPopUpButtonCell

I have a dynamic NSTableView which can add a number of columns depending on the data provided. For each column I have set the header cell to be a NSPopUpButtonCell. (Side-note: I've had to use a custom subclass class for NSTableHeaderView otherwise the menu doesn't pop-up). All works well, apart from a duplicate or extra header button cell on the top right. It mirrors perfectly the previous column selection as shown in screenshots. My question is how do I stop the NSTableView from recycling the previous popup header cell? (By the way I have tried the setCornerView method but that only effects the header area above the vertical scrollbar.)
I came across the same problem this week. I went with the quick fix,
[_tableView sizeLastColumnToFit];
(However, after discussion with OP this requires that you use a subclass of NSPopUpButtonCell in the header and also NSTableHeaderView. I attach my solution below)
You can to this by combining the approaches outlined here,
PopUpTableHeaderCell
DataTableHeaderView
Here is a simplified snippet,
// PopUpTableHeaderCell.h
#import <Cocoa/Cocoa.h>
/* Credit: http://www.cocoabuilder.com/archive/cocoa/133285-placing-controls-inside-table-header-view-solution.html#133285 */
#interface PopUpTableHeaderCell : NSPopUpButtonCell
#property (strong) NSTableHeaderCell *tableHeaderCell; // Just used for drawing the background
#end
// PopUpTableHeaderCell.m
#implementation PopUpTableHeaderCell
- (id)init {
if (self = [super init]){
// Init our table header cell and set a blank title, ready for drawing
_tableHeaderCell = [[NSTableHeaderCell alloc] init];
[_tableHeaderCell setTitle:#""];
// Set up the popup cell attributes
[self setControlSize:NSMiniControlSize];
[self setArrowPosition:NSPopUpNoArrow];
[self setBordered:NO];
[self setBezeled:NO];
[self setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
}
return self;
}
// We do all drawing ourselves to make our popup cell look like a header cell
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView{
[_tableHeaderCell drawWithFrame:cellFrame inView:controlView];
// Now draw the text and image over the top
[self drawInteriorWithFrame:cellFrame inView:controlView];
}
#end
Now for the NSTableViewHeader subclass.
//DataTableHeaderView.h
#import <Cocoa/Cocoa.h>
/* Credit: http://forums.macnn.com/79/developer-center/304072/problem-of-nspopupbuttoncell-within-nstableheaderview/ */
#interface DataTableHeaderView : NSTableHeaderView
#end
//DataTableHeaderView.m
#import "DataTableHeaderView.h"
/* Credit: http://forums.macnn.com/79/developer-center/304072/problem-of-nspopupbuttoncell-within-nstableheaderview/ */
#implementation DataTableHeaderView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)mouseDown:(NSEvent *)theEvent {
// Figure which column, if any, was clicked
NSPoint clickedPoint = [self convertPoint:theEvent.locationInWindow fromView:nil];
NSInteger columnIndex = [self columnAtPoint:clickedPoint];
if (columnIndex < 0) {
return [super mouseDown:theEvent];
}
NSRect columnRect = [self headerRectOfColumn:columnIndex];
// I want to preserve column resizing. If you do not, remove this
if (![self mouse:clickedPoint inRect:NSInsetRect(columnRect, 3, 0)]) {
return [super mouseDown:theEvent];
}
// Now, pop the cell's menu
[[[self.tableView.tableColumns objectAtIndex:columnIndex] headerCell] performClickWithFrame:columnRect inView:self];
[self setNeedsDisplay:YES];
}
- (BOOL)isOpaque {
return NO;
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Drawing code here.
}
#end
You can tie everything together in the AppDelegate -awakeFromNib or similar,
-(void) awakeFromNib {
/* NB the NSTableHeaderView class is changed to be an DataTableHeaderView in IB! */
NSUInteger numberOfColumnsWanted = 5;
for (NSUInteger i=0; i<numberOfColumnsWanted; i++) {
PopUpTableHeaderCell *headerCell;
headerCell = [[PopUpTableHeaderCell alloc] init];
[headerCell addItemWithTitle:#"item 1"];
[headerCell addItemWithTitle:#"item 2"];
[headerCell addItemWithTitle:#"item 3"];
NSTableColumn *column;
[column setHeaderCell:headerCell];
[column sizeToFit];
[_tableView addTableColumn:column];
}
/* If we don't do this we get a final (space filling) column with an unclickable (dummy) header */
[_tableView sizeLastColumnToFit];
}
Other than that I haven't figured out how to properly correct the drawing in that region.
It seems like it's the image of the last cell that is being duplicated. So I slightly more hack-ish approach would be to add a extra column to your table view with a blank name and which intentionally ignores the mouse clicks. Hopefully by setting the display properties of the last column you can make it look the way you want.
I couldn't find any NSTableView or NSTableViewDelegate method that allow control of this region, so may any other solution would be very complicated. I would be interested in a nice solution too, but I hope this gets you started!
I have this issue and i don't use NSPopUpButtonCell at all.
I just want to tell about other method how to hide this odd header. This methods will not remove an odd table column, i.e. if you have 2 'legal' columns and hide this extra 3rd column header, you will still be able to move separator between 2nd and 3rd column. But in this case you won't see redundant header even if you want to resize any column.
I still need solution how to completely remove the redundant column, and why this is happening. (and why Apple won't fix this bug?)
So... you can just calculate index of column which this header belongs to and according to this draw your header or don't. First, subclass NSTableHeaderCell and set it as a cell class for columns. Let assume your subclass named TableHeaderCell:
for column in self.tableView.tableColumns {
let col:NSTableColumn = column as! NSTableColumn
//you can operate with header cells even for view-based tableView's
//although the documentation says otherwise.
col.headerCell = TableHeaderCell(textCell: col.title)
//or what initialiser you will have
}
Then in TableHeaderCell's drawWithFrame method you should have:
override func drawWithFrame(cellFrame: NSRect, inView controlView: NSView) {
let headerView = controlView as! HashTableHeaderView
let columnIndex = headerView.columnAtPoint(cellFrame.origin)
if columnIndex == -1 {
return
}
//parent's drawWithFrame or your own draw logic:
super.drawWithFrame(cellFrame, inView: controlView)
}
After this you won't have redundant header drawn because it not belongs to any column and columnAtPoint method will return -1.

Dont deselect a selected row in view based NStableview when clicked outside

In my view based NSTableView i don't want to deselect the selected cell, when clicking in an empty part of the NSTableView, how to obey this default behavior?
Improved version from Neha's answer (this obeys the select / deselect)
Subclass NSTableView and implement :
- (void)mouseDown:(NSEvent *)theEvent {
NSPoint globalLocation = [theEvent locationInWindow];
NSPoint localLocation = [self convertPoint:globalLocation fromView:nil];
NSInteger clickedRow = [self rowAtPoint:localLocation];
if(clickedRow != -1) {
[super mouseDown:theEvent];
}
}
We just ignore the event, when we don't hit a row...
Implement the mouse down event of your NSTableView by subclassing it. Inside it check if the clicked point is a row or empty area. If it is an empty area, then again select the previously selected rows of your table view.
- (void)mouseDown:(NSEvent *)theEvent
{
NSPoint globalLocation = [theEvent locationInWindow];
NSPoint localLocation = [self convertPoint:globalLocation fromView:nil];
NSInteger clickedRow = [self rowAtPoint:localLocation];
NSIndexSet* selectedRows = [self selectedRowIndexes];
NSLog(#"%ld",clickedRow);
[super mouseDown:theEvent];
if(clickedRow == -1)
{
[self selectRowIndexes:selectedRows byExtendingSelection:NO];
}
}
This the Swift4 version if anyone needs it:
override func mouseDown(with event: NSEvent) {
let globalLocation = event.locationInWindow
let localLocation = convert(globalLocation, from: nil)
let clickedRow = row(at: localLocation)
if clickedRow != -1 {
super.mouseDown(with: event)
}
}

NSTableView hit tab to jump from row to row while editing

I've got an NSTableView. While editing, if I hit tab it automatically jumps me to the next column. This is fantastic, but when I'm editing the field in the last column and I hit tab, I'd like focus to jump to the first column of the NEXT row.
Any suggestions?
Thanks to Michael for the starting code, it was very close to what ended up working! Here is the final code that I used, hope it will be helpful to someone else:
- (void) textDidEndEditing: (NSNotification *) notification {
NSInteger editedColumn = [self editedColumn];
NSInteger editedRow = [self editedRow];
NSInteger lastColumn = [[self tableColumns] count] - 1;
NSDictionary *userInfo = [notification userInfo];
int textMovement = [[userInfo valueForKey:#"NSTextMovement"] intValue];
[super textDidEndEditing: notification];
if ( (editedColumn == lastColumn)
&& (textMovement == NSTabTextMovement)
&& editedRow < ([self numberOfRows] - 1)
)
{
// the tab key was hit while in the last column,
// so go to the left most cell in the next row
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:(editedRow+1)] byExtendingSelection:NO];
[self editColumn: 0 row: (editedRow + 1) withEvent: nil select: YES];
}
}
You can do this without subclassing by implementing control:textView:doCommandBySelector:
-(BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector {
if(commandSelector == #selector(insertTab:) ) {
// Do your thing
return YES;
} else {
return NO;
}
}
(The NSTableViewDelegate implements the NSControlTextEditingDelegate protocol, which is where this method is defined)
This method responds to the actual keypress, so you're not constrained to the textDidEndEditing method, which only works for text cells.
Subclass UITableView and add code to catch the textDidEndEditing call.
You can then decide what to do based on something like this:
- (void) textDidEndEditing: (NSNotification *) notification
{
NSDictionary *userInfo = [notification userInfo];
int textMovement = [[userInfo valueForKey:#"NSTextMovement"] intValue];
if ([self selectedColumn] == ([[self tableColumns] count] - 1))
(textMovement == NSTabTextMovement)
{
// the tab key was hit while in the last column,
// so go to the left most cell in the next row
[yourTableView editColumn: 0 row: ([self selectedRow] + 1) withEvent: nil select: YES];
}
[super textDidEndEditing: notification];
[[self window] makeFirstResponder:self];
} // textDidEndEditing
This code isn't tested... no warranties... etc. And you might need to move that [super textDidEndEditing:] call for the tab-in-the-right-most-cell case. But hopefully this will help you to the finish line. Let me know!

Resources