Search code examples
objective-ccocoansoutlineview

NSOutlineView view based - Show button only when selected


I have a NSOutlineView view-based with one column Header + image / text / button

I want to show the button only when the item is selected.

I use the following code :

- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item {
   ....
  SidebarTableCellView *sidebarTableCellView = [outlineView makeViewWithIdentifier:@"MainCell" owner:self];
  [sidebarTableCellView.buttonProgramme setHidden:YES];
  if (outlineView.selectedRow == [outlineView rowForItem:item])
            [sidebarTableCellView.buttonProgramme setHidden:NO];

But it doesn't work, the button is always hidden! I can' figure out what is the issue ?

EDIT: breakpoint in the if statement => If statement Never match


Solution

  • I managed to solve my issue by adding the following code (No change in viewForTableColumn):

    - (void)outlineViewSelectionDidChange:(NSNotification *)notification {
    
        NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
        [center removeObserver:self
                          name:@"NSOutlineViewSelectionDidChangeNotification"
                        object:self.sidebarOutlineView];
    
        NSInteger s = [self.sidebarOutlineView selectedRow];
        NSInteger lastSelectedRow = [[self.globalVariableDictionary objectForKey:@"lastSelectedRow"] integerValue];
        [self.globalVariableDictionary setObject:[NSNumber numberWithInteger:s] forKey:@"lastSelectedRow"];
    
        [self.sidebarOutlineView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:s]
                                           columnIndexes:[NSIndexSet indexSetWithIndex:0]];
        [self.sidebarOutlineView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:lastSelectedRow]
                                           columnIndexes:[NSIndexSet indexSetWithIndex:0]];
        [self.sidebarOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:s] byExtendingSelection:NO];
    
        [center addObserver:self
                   selector:@selector(outlineViewSelectionDidChange:)
                       name:@"NSOutlineViewSelectionDidChangeNotification"
                     object:self.sidebarOutlineView];
    
        [center addObserver:self
                   selector:@selector(outlineViewSelectionDidChange:)
                       name:@"NSOutlineViewSelectionDidChangeNotification"
                     object:self.sidebarOutlineView];
    }
    

    By doing this, we force the call of viewForTableColumn: when a user change the selection.

    Thanks !