-->

Automatically adjust size of NSTableView

2020-07-17 06:34发布

问题:

I have an NSTableView, which should resize it's frame when a row is added. I would make 2 properties, maxHeight and minHeight, and if any rows are being added or removed, I would resize the table view to fit it's content, if it doesn't cross the limit.

Like the Safari Download Panel (10.7 or later). Has anyone an idea how to do this? I would want to handle this in a subclass. So no messing with the resizing in the delegate class.

I would at least need to know which method is being called when the table view is being reloaded. reloadTable only invokes the real reloading method, so no success there.

回答1:

I did something similar a while back and I did it on the controller, not on a subclass (sorry if it's not what you're looking for). Basically I wrote a method that computed the height of the tableview by adding the height of all the rows. And every time I added or removed a row from the table I'd call that method. Here is something to get you started:

- (void)adjustTableSize
{
    NSInteger minHeight = ...
    NSInteger maxHeight = ...

    NSInteger tViewHeight = 0;
    for (int i = 0; i < [tableView numberOfRows]; i++) {
        NSView* v = [tableView viewAtColumn: 0 row: i makeIfNecessary: YES]; // Note that this is for view-based tableviews
        tViewHeight += v.frame.size.height;
    }

    NSInteger result = MIN(MAX(tViewHeight, minHeight), maxHeight);

    // Do something with result here
}

If you really want it on a subclass it should possible, but it might be a pain to work out how...

EDIT:

If you don't mind working with undocummented APIs, here's a simpler version:

- (void)adjustTableSize
{
    NSInteger minHeight = ...
    NSInteger maxHeight = ...
    NSInteger result = MIN(MAX([tableView _minimumFrameSize].height, minHeight), maxHeight);

    // Do something with result here
}

Since this is undocummented I can't promise it'll work, but from my testing so far it does. And it might be faster than creating views just to get their height, specially if you have lots of rows.