Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autosize columns in a view-based NSTableView or NSOutlineView

What is required to support the column autosize request for a view-based table? The docs are really unclear on this point, and seem to speak to cell-based views.

This is to handle a double click on a column separator.

I can make this work by implementing tableView:sizeToFitWidthOfColumn: for an NSTableView and outlineView:sizeToFitWidthOfColumn: for an NSOutlineView, but the docs say this is only necessary for large tables. Is there a more correct way to do this?

- (CGFloat)tableView:(NSTableView*)tableView sizeToFitWidthOfColumn:(NSInteger)column {
  NSUInteger n = [self numberOfRowsInTableView:tableView];
  CGFloat w = 30;
  NSTableColumn* col = [[tableView tableColumns] objectAtIndex:column];
  for (int i=0; i<MIN(n, 100); ++i) {
    NSView* vw = [self tableView:tableView viewForTableColumn:col row:i];
    w = MAX(w, [vw frame].size.width);
  }
  return w;
}
like image 778
jeberle Avatar asked Feb 21 '14 19:02

jeberle


1 Answers

I was wondering this same thing. If you do some digging in the assembly you’ll discover that the framework method responsible for the column autosizing functionality is -[NSTableView _sizeToFitWidthOfColumn:]. Unfortunately, the first thing it does is check whether the table view is a view-based table view and, if so, it simply jumps to the end of the method and does absolutely nothing.

View-based table views were introduced in OS X 10.6 in 2009. Alas, five years later and it looks this functionality still hasn’t been reimplemented.

like image 75
Cody Robbins Avatar answered Nov 14 '22 03:11

Cody Robbins