在基于视图的表视图中响应文本字段中的鼠标事件

时间:2011-08-18 00:56:46

标签: cocoa nstableview nstextfield mousedown

我在NSOutlineView内的自定义视图中有文本字段。编辑其中一个单元格需要单击,暂停和另一次单击。第一次单击选择表视图行,第二次单击单击在字段中绘制光标。双击单元格,您可以在基于单元格的表格视图中进行编辑,只选择该行。

我想要的行为:点击一下即可更改选择并进行编辑。

我需要覆盖什么才能获得此行为?

我已经阅读了其他一些帖子:

  • NSTextField flyweight pattern似乎不适用于基于视图的表视图,其中单元格视图都是从nib实例化的。
  • 我尝试将NSTextField作为this solution describes进行子类化,但未调用我重写的mouseDown方法。被覆盖的awakeFromNibviewWillDraw(在this post中提及)调用。当然,如果我将文本字段放在表视图之外的某个位置,则会调用mouseDown

相比之下,我的单元格视图中的NSSegmentedControl会在不先选择行的情况下更改其值。


以下是工作解决方案改编自已接受的回复:

在大纲视图子类中:

-(void)mouseDown:(NSEvent *)theEvent {
    [super mouseDown:theEvent];

    // Forward the click to the row's cell view
    NSPoint selfPoint = [self convertPoint:theEvent.locationInWindow fromView:nil];
    NSInteger row = [self rowAtPoint:selfPoint];
    if (row>=0) [(CellViewSubclass *)[self viewAtColumn:0 row:row makeIfNecessary:NO]
            mouseDownForTextFields:theEvent];
}

在表格单元格视图子类中:

// Respond to clicks within text fields only, because other clicks will be duplicates of events passed to mouseDown
- (void)mouseDownForTextFields:(NSEvent *)theEvent {
    // If shift or command are being held, we're selecting rows, so ignore
    if ((NSCommandKeyMask | NSShiftKeyMask) & [theEvent modifierFlags]) return;
    NSPoint selfPoint = [self convertPoint:theEvent.locationInWindow fromView:nil];
    for (NSView *subview in [self subviews])
        if ([subview isKindOfClass:[NSTextField class]])
            if (NSPointInRect(selfPoint, [subview frame]))
                [[self window] makeFirstResponder:subview];
}

6 个答案:

答案 0 :(得分:15)

我会尝试返回favor ...子类NSOutlineView并覆盖-mouseDown:,如下所示:

- (void)mouseDown:(NSEvent *)theEvent {
    [super mouseDown:theEvent];

    // Only take effect for double clicks; remove to allow for single clicks
    if (theEvent.clickCount < 2) {
        return;
    }

    // Get the row on which the user clicked
    NSPoint localPoint = [self convertPoint:theEvent.locationInWindow
                                   fromView:nil];
    NSInteger row = [self rowAtPoint:localPoint];

    // If the user didn't click on a row, we're done
    if (row < 0) {
        return;
    }

    // Get the view clicked on
    NSTableCellView *view = [self viewAtColumn:0 row:row makeIfNecessary:NO];

    // If the field can be edited, pop the editor into edit mode
    if (view.textField.isEditable) {
        [[view window] makeFirstResponder:view.textField];
    }
}

答案 1 :(得分:14)

有同样的问题。经过多次努力之后,当我选择None而不是默认Regular(其他选项为Source List)时,它在IB中的表格视图的Highlight选项中神奇地起作用了! / p>

另一种选择是https://stackoverflow.com/a/13579469/804616的解决方案,与此相比,它似乎更具体,但有点骇人听闻。

答案 2 :(得分:4)

您真的想要覆盖validateProposedFirstResponder并允许根据您的逻辑制作(或不制作)特定的第一响应者。 NSTableView中的实现是这样的(有点像)(我将它重写为伪代码):

- (BOOL)validateProposedFirstResponder:(NSResponder *)responder forEvent:(NSEvent *)event {

// We want to not do anything for the following conditions:
// 1. We aren't view based (sometimes people have subviews in tables when they aren't view based)
// 2. The responder to valididate is ourselves (we send this up the chain, in case we are in another tableview)
// 3. We don't have a selection highlight style; in that case, we just let things go through, since the user can't appear to select anything anyways.
if (!isViewBased || responder == self || [self selectionHighlightStyle] == NSTableViewSelectionHighlightStyleNone) {
    return [super validateProposedFirstResponder:responder forEvent:event];
}

if (![responder isKindOfClass:[NSControl class]]) {
    // Let any non-control become first responder whenever it wants
    result = YES;
    // Exclude NSTableCellView. 
    if ([responder isKindOfClass:[NSTableCellView class]]) {
        result = NO;
    }

} else if ([responder isKindOfClass:[NSButton class]]) {
    // Let all buttons go through; this would be caught later on in our hit testing, but we also do it here to make it cleaner and easier to read what we want. We want buttons to track at anytime without any restrictions. They are always valid to become the first responder. Text editing isn't.
    result = YES;
} else if (event == nil) {
    // If we don't have any event, then we will consider it valid only if it is already the first responder
    NSResponder *currentResponder = self.window.firstResponder;
    if (currentResponder != nil && [currentResponder isKindOfClass:[NSView class]] && [(NSView *)currentResponder isDescendantOf:(NSView *)responder]) {
        result = YES;
    }
} else {
    if ([event type] == NSEventTypeLeftMouseDown || [event type] == NSEventTypeRightMouseDown) {
        // If it was a double click, and we have a double action, then send that to the table
        if ([self doubleAction] != NULL && [event clickCount] > 1) {
           [cancel the first responder delay];
        }
   ...
          The code here checks to see if the text field 
        cell had text hit. If it did, it attempts to edit it on a delay. 
        Editing is simply making that NSTextField the first responder.
        ...

     }

答案 3 :(得分:3)

我编写了以下内容来支持这样的情况:当你有一个更复杂的NSTableViewCell有多个文本字段或文本字段没有占据整个单元格时。这里有一个用于翻转y值的技巧,因为当您在NSOutlineView或NSTableView和它的NSTableCellViews之间切换时,坐标系统会被翻转。

- (void)mouseDown:(NSEvent *)theEvent
{
    [super mouseDown: theEvent];

    NSPoint thePoint = [self.window.contentView convertPoint: theEvent.locationInWindow
                                                      toView: self];
    NSInteger row = [self rowAtPoint: thePoint];
    if (row != -1) {
        NSView *view = [self viewAtColumn: 0
                                      row: row
                          makeIfNecessary: NO];

        thePoint = [view convertPoint: thePoint
                             fromView: self];
        if ([view isFlipped] != [self isFlipped])
            thePoint.y = RectGetHeight(view.bounds) - thePoint.y;

        view = [view hitTest: thePoint];
        if ([view isKindOfClass: [NSTextField class]]) {
            NSTextField *textField = (NSTextField *)view;
            if (textField.isEnabled && textField.window.firstResponder != textField)

                dispatch_async(dispatch_get_main_queue(), ^{
                    [textField selectText: nil];
                });
        }
    }
}

答案 4 :(得分:1)

只是想指出,如果您想要的只是编辑(即在没有选择的表中),覆盖-hitTest:似乎更简单,更像Cocoa:

- (NSView *)hitTest:(NSPoint)aPoint
{
    NSInteger column = [self columnAtPoint: aPoint];
    NSInteger row = [self rowAtPoint: aPoint];

    // Give cell view a chance to override table hit testing
    if (row != -1 && column != -1) {
        NSView *cell = [self viewAtColumn:column row:row makeIfNecessary:NO];

        // Use cell frame, since convertPoint: doesn't always seem to work.
        NSRect frame = [self frameOfCellAtColumn:column row:row];
        NSView *hit = [cell hitTest: NSMakePoint(aPoint.x + frame.origin.x, aPoint.y + frame.origin.y)];

        if (hit)
            return hit;
    }

    // Default implementation
    return [super hitTest: aPoint];
}

答案 5 :(得分:1)

这是@Dov答案的 swift 4.2 版本:

 override func mouseDown(with event: NSEvent) {
    super.mouseDown(with: event)

    if (event.clickCount < 2) {
        return;
    }
    // Get the row on which the user clicked
    let localPoint = self.convert(event.locationInWindow, from: nil)


    let row = self.row(at: localPoint)

    // If the user didn't click on a row, we're done
    if (row < 0) {
        return
    }

    DispatchQueue.main.async {[weak self] in
        guard let self = self else {return}
        // Get the view clicked on
        if let clickedCell = self.view(atColumn: 0, row: row, makeIfNecessary: false) as? YourOutlineViewCellClass{

            let pointInCell = clickedCell.convert(localPoint, from: self)

            if (clickedCell.txtField.isEditable && clickedCell.txtField.hitTest(pointInCell) != nil){

                clickedCell.window?.makeFirstResponder(clickedCell.txtField)

            }

        }
    }

}