Entry
How do i get sort arrows in the header of my NSTableView?
May 16th, 2002 00:50
Ben Hines, http://cocoa.mamasam.com/COCOADEV/2001/11/2/18932.php
// per Chuck Pistula on Cocoadev list, this is the "right" way to find the sort image as of 10.1
// This uses internal stuff, so make sure you save a local copy of the sort images, in case the "_defaultTableHeaderSortImage" goes away in 10.2.
if ([[NSTableView class] respondsToSelector: @selector(_defaultTableHeaderSortImage)])
{
upSortImage = [[[NSTableView class] performSelector:@selector(_defaultTableHeaderSortImage)] retain];
} else {
upSortImage = [[NSImage alloc] initWithContentsOfFile:[inBundle pathForResource:@"sort-up" ofType:@"tiff"]];
}
if ([[NSTableView class] respondsToSelector: @selector(_defaultTableHeaderReverseSortImage)])
{
downSortImage = [[[NSTableView class] performSelector:@selector(_defaultTableHeaderReverseSortImage)] retain];
} else {
downSortImage = [[NSImage alloc] initWithContentsOfFile:[inBundle pathForResource:@"sort-down" ofType:@"tiff"]];
}
Then you can sort your tableview like this:
// -----------------------------------------------------------------------------
//
// - (void) tableView:(NSTableView*) didClickTableColumn:(NSTableColumn *)\
//
// Called when a table header cell is clicked.
// (note this will apparently not be called if the table columns are not re-orderable)
- (void) tableView:(NSTableView*)tableView didClickTableColumn:(NSTableColumn *)tableColumn
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// check to see if this column was already the selected one and if so invert the sort function.
if ([currentSortedColumn_ isEqualToString:[tableColumn identifier]] == YES)
{
if(upSort) upSort = FALSE; else upSort = TRUE;
}
else
{ // if there already was a sorted column, remove the indicator image from it.
[tableView setIndicatorImage:nil inTableColumn:[oTable tableColumnWithIdentifier:currentSortedColumn_]];
upSort = TRUE;
}
// set the highlight+indicator image in the newly selected column
[tableView setHighlightedTableColumn:tableColumn];
if(upSort)
[tableView setIndicatorImage:upSortImage inTableColumn:tableColumn];
else
[tableView setIndicatorImage:downSortImage inTableColumn:tableColumn];
[currentSortedColumn_ setString:[[tableColumn identifier] retain]];
[mResultArray sortUsingFunction:(int (*)(id, id, void *))(sortDictArray) context:self];
[tableView reloadData];
[defaults setObject:currentSortedColumn_ forKey:kResultsSortColumn];
[defaults synchronize];
}