开发者

NSButtonCell created programmatically doesn't highlight when clicked

I wanted to have a button appear in a table view as the first element on the last row instead of the normal data, so I created a subclass of NSTableView and overwrote the preparedCellAtColumn:row: method to generate the desired behaviour on the last row.

- (NSCell *)preparedCellAtColumn:(NSInteger)column row:(NSInteger)row {
    if(row < [self numberOfRows]-1) {
        return [super preparedCellAtColumn:column row:row];
    } else {
        // if we're on the last row, we're going to add the button instead of data
        if(column == 0) {
            NSButtonCell *button = [[NSButtonCell alloc] initTextCell:self.buttonTitle];
            [button setEditable:YES];
            [button setSelectable:YES];
            [button setBezelStyle:NSTexturedSquareBezelStyle];
            [button setGradientType:NSGradientConvexWeak];
            [button setButtonType:NSMomentaryPushInButton];
            [button setHighlightsBy:NSBackgroundStyleLowered];
            [button setAction:@selector(openAddDialog)];
            [button setControlView:self];
            return button;
        } else {
            NSTextFieldCell *emptyCell = [[NSTextFieldCell alloc] initTextCell:@""];
            [emptyCell setEditable:NO];
            [emptyCell setSelectable:NO];
            return emptyCell;
        }
    }
}

Fortunately, the functionality works--the button appears on the last row, and it calls the openAddDialog selector when it is clicked. There are two visual problems, however:

1. The button doesn't highlight (press down) when it's clicked.

2. The table selects the row with the button on it when it is clicked.

I'm still pretty new to Objective C and Cocoa, so I'm not really sure where to look for the solutions to these. Why isn't the button's setHighlighted method getting called when it is clicked? What method is called just before the NSTableView selects a row so I can override it and tell it not to select the last row?

I ended up solving my second question by overriding the selectRowIndexes:byExtendingSelection: function in my开发者_C百科 table subclass and simply not passing the last row index on to the super function.


I'm pretty sure you have to make the column editable in order to activate a UI element inside of it.

BTW, it's usually a bad idea to put some kind of control at the end of a table, especially one that affects the entire table. Tables should be composed of logical repeating units. Putting something unique in a table causes user confusion and can hide functionality. You most likely want to move the button outside the table itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜