NSTableColumn size to fit contents

Dov picture Dov · Jan 12, 2011 · Viewed 15k times · Source

I am developing in and against Mac OS X 10.6 (Snow Leopard). When I double-click between two of my NSTableView's column headers, the column on the left autosizes, like you would expect.

I want to provide this in a context menu as well, but it seems there is no publicly accessible function to do this. I've Googled, and looked at the documentation for NSTableView, NSTableHeaderView, and NSTableColumn, but found nothing. I find it hard to believe they wouldn't expose something so useful when they obviously have the code written to do it.

I saw the -[NSTableColumn sizeToFit] method, but that only takes the header's size into account. I would also settle for sending the double-click event to the NSTableHeaderView, but couldn't figure out how to do that, either.

Update - I realized it's important to mention I have an NSArrayController (subclass) providing the data to my table, so I don't have an NSTableViewDataSource on which I could call -[tableView: objectValueForTableColumn: row:]. That is the crux of the problem: each column is bound to a keypath of the array controller and that's how it gets its data, so it can't loop through its contents.

Answer

Raiyan Kabir picture Raiyan Kabir · Jan 22, 2011

You can get the length of each cell by getting the cells from the column.

NSCell myCell = [column dataCellForRow:i];

Then get the width of the cell.

width = [myCell cellSize].width;

After that you can set the width of the cell as the width of the column.

[column setMinWidth:width];
[column setWidth:width];