2

我想在双击列标题时更改表格视图列标题文本。为此,我创建了一个 NSTableHeaderCell 的子类,例如-

@interface NBETableHeaderCell : NSTableHeaderCell<NSTextFieldDelegate,NSTableViewDelegate>
@end

#import "NBETableHeaderCell.h"
@implementation NBETableHeaderCell

- (void)textDidEndEditing:(NSNotification *)notification
{
    NSTextView *editor = notification.object;
    [self setTitle:editor.string];
    [self setHighlighted:NO];
    [self endEditing:editor];
}

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    if([self isHighlighted])
    {
        [self drawFocusRingMaskWithFrame:cellFrame inView:controlView.superview];
    }

    [super drawWithFrame:cellFrame inView:controlView];
}

- (void)drawFocusRingMaskWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    [controlView lockFocus];
    NSSetFocusRingStyle(NSFocusRingOnly);
    [[NSBezierPath bezierPathWithRect:cellFrame] fill];
    [controlView unlockFocus];
}
@end

我设置表格列标题单元格类

-(void)setupTableHeader:(id)table {
    NSArray *columns = [table tableColumns];
    NSEnumerator *cols = [columns objectEnumerator];
    NSTableColumn *col = nil;

    NBETableHeaderCell *iHeaderCell;

    while (col = [cols nextObject]) {
        iHeaderCell = [[NBETableHeaderCell alloc] initTextCell:[[col headerCell] stringValue]];
        [col setHeaderCell:iHeaderCell];
        [[col headerCell] setEditable:YES];
        [iHeaderCell release];
    }
    [table setTarget:self];
    [table setDoubleAction:@selector(doubleClickInTableView:)];
}

我设置的双击动作是:

- (void)doubleClickInTableView:(id)sender
{
    NSInteger row = [myTableView clickedRow];
    NSInteger column = [myTableView clickedColumn];

    if(row == -1&& column >= 0)
    {
        NSTableColumn *tableColumn = [[myTableView tableColumns] objectAtIndex:column];
        NSTableHeaderView *headerView = [myTableView headerView];
        NBETableHeaderCell *headerCell = [tableColumn headerCell];
        id cellEditor = [self.view.window fieldEditor:YES forObject:myTableView];
        [headerCell setHighlighted:YES];
        [headerCell selectWithFrame:[headerView headerRectOfColumn:column]
                             inView:headerView
                             editor:cellEditor
                           delegate:headerCell
                              start:0
                             length:headerCell.stringValue.length];

        [cellEditor setDrawsBackground:YES];
    }
}

现在,我可以编辑列标题并设置新文本。在标记出新文本时仍然存在。但是,如果我设置了一个新文本,而不是点击其他表格列标题,我的文本不会更改,旧值将被保留。这可能是因为- (void)textDidEndEditing:(NSNotification *)notification在选择其他表列标题时未调用委托。这个委托只在跳出时被调用。请建议,如何在表格列标题单元格中设置新值而不用制表符?

4

0 回答 0