Search code examples
macoscocoatagsnsbutton

OSX: NSButton with tag is not recognized


I have a NSButton inside my cell in a NSTableView and I want to assign to it an action and a tag to have an index so I done:

NSTableCellView *cellView = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    if( [tableColumn.identifier isEqualToString:@"check"] )
    {
        NSButton *button = (NSButton*)[cellView viewWithTag:100];

        if (button == nil)
            NSLog(@"button is null");
        [button setTag:row];
        [button setAction:@selector(SelectRow:)];
    }

}

- (IBAction)SelectRow:(id)sender{

    NSInteger index = [sender tag];

    NSLog(@"index:%lu", index);
}

You can see that I have the NSButton that start with tag = 100: I set it in xib file, and I change it for its row value. But I have a button nil because it enter in the condition. In IOS this work fine but in OSX not... why?


Solution

  • If you only need the tag to get the right row index, then I may have another solution for you. I needed to figure out a view with a button press as well. Instead of using tags, I just asked the table view for the index of the buttons superview. For me, this was the better approach because of cells changing order..

    - (IBAction)selectRow:(NSButton *)sender {
         NSInteger row = [_tableView rowForView:sender.superview];
         NSLog(@"index:%lu", index);
    }
    

    I hope I was able to help you!