Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select items in NSOutlineView without NSTreeController?

I'm using NSOutlineView without NSTreeController and have implemented my own datasource. What is the best way to select an item? NSOutlineView support already expandItem: and collapseItem:. And I'm missing a handy method like `selectItem:. How can I do it programatically ?

Thank you.

like image 888
cocoafan Avatar asked Jul 08 '09 08:07

cocoafan


3 Answers

Here is how I finally ended up. Suggestions and corrections are always welcome.

@implementation NSOutlineView (Additions)

- (void)expandParentsOfItem:(id)item {
    while (item != nil) {
        id parent = [self parentForItem: item];
        if (![self isExpandable: parent])
            break;
        if (![self isItemExpanded: parent])
            [self expandItem: parent];
        item = parent;
    }
}

- (void)selectItem:(id)item {
    NSInteger itemIndex = [self rowForItem:item];
    if (itemIndex < 0) {
        [self expandParentsOfItem: item];
        itemIndex = [self rowForItem:item];
        if (itemIndex < 0)
            return;
    }

    [self selectRowIndexes: [NSIndexSet indexSetWithIndex: itemIndex] byExtendingSelection: NO];
}
@end
like image 125
cocoafan Avatar answered Oct 09 '22 19:10

cocoafan


Remember to look in superclasses when you can't find something. In this case, one of the methods you need comes from NSTableView, which is NSOutlineView's immediate superclass.

The solution is to get the row index for the item using rowForItem:, and if it isn't -1 (item not visible/not found), create an index set with it with [NSIndexSet indexSetWithIndex:] and pass that index set to the selectRowIndexes:byExtendingSelection: method.

like image 25
Peter Hosey Avatar answered Oct 09 '22 19:10

Peter Hosey


No, there isn't a selectItem: method, but there is an rowForItem: method. If you combine that with Peter's advice about using selectRowIndexes:byExtendingSelection: above, you should have all the information you need.

If you really wanted to have a method to select an item, which I would recommend calling setSelectedItem: for consistency's sake, you could write something like this in a category on NSOutlineView

- (void)setSelectedItem:(id)item {
    NSInteger itemIndex = [self rowForItem:item];
    if (itemIndex < 0) {
        // You need to decide what happens if the item doesn't exist
        return;
    }

    [self selectRowIndexes:[NSIndexSet indexSetWithIndex:itemIndex] byExtendingSelection:NO];
}

I have no idea if this code actually works; I just dashed it off to illustrate the concept.

like image 2
Alex Avatar answered Oct 09 '22 17:10

Alex