【问题标题】:How to select a row in an NSTableView when clicking on an NSTextView inside an NSTableCellView?单击 NSTableCellView 中的 NSTextView 时如何在 NSTableView 中选择一行?
【发布时间】:2012-04-17 02:00:26
【问题描述】:

我有一个基于视图的单列 NSTableView。在我的 NSTableCellView 子类中,我有一个可选择但不可编辑的 NSTextView。

当用户直接点击 NSTableCellView 时,该行会正确突出显示。但是当用户点击该 NSTableCellView 中的 NSTextView 时,该行不会突出显示。

如何让 NSTextView 上的点击传递给 NSTableCellView 以使该行突出显示?

类层次结构如下: NSScrollView > NSTableView > NSTableColumn > NSTableCellView > NSTextView

【问题讨论】:

  • 我无法复制您所看到的内容。当我将文本字段添加到基于视图的单元格时,单击它会选择行而不是文本字段(我必须再次单击才能发生这种情况)。您是否将其绑定到任何东西,或者您是否使用数据源?
  • 我使用的是 NSTextView,而不是 NSTextField。是的,我的行为与您对文本字段的行为相同,但我的应用程序需要文本视图。

标签: cocoa nstableview nstextview


【解决方案1】:

这就是我最终要做的。我做了一个NSTextView的子类并覆盖mouseDown:如下...

- (void)mouseDown:(NSEvent *)theEvent
{
    // Notify delegate that this text view was clicked and then
    // handled the click natively as well.
    [[self myTextViewDelegate] didClickMyTextView:self];
    [super mouseDown:theEvent];
}

我正在重用 NSTextView 的标准委托...

- (id<MyTextViewDelegate>)myTextViewDelegate
{
    // See the following for info on formal protocols:
    // stackoverflow.com/questions/4635845/how-to-add-a-method-to-an-existing-protocol-in-cocoa
    if ([self.delegate conformsToProtocol:@protocol(MyTextViewDelegate)]) {
        return (id<MyTextViewDelegate>)self.delegate;
    }
    return nil;
}

在标题中...

@protocol MyTextViewDelegate <NSTextViewDelegate>
- (void)didClickMyTextView:(id)sender;
@end

在委托中,我实现了 didClickMyTextView: 来选择行。

- (void)didClickMyTextView:(id)sender
{
    // User clicked a text view. Select its underlying row.
    [self.tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:[self.tableView rowForView:sender]] byExtendingSelection:NO];
}

【讨论】:

  • 整洁 -- 一个事件中的两个不冲突的操作。您已经创建了一种适用于多种情况的设计模式。
  • 一个解决所有问题的方法,很好的解决方案。
【解决方案2】:

或者,使用 NSTextField,然后,

textfield.bezeled = NO;
textfield.drawsBackground = NO;
textfield.editable = NO;
textfield.selectable = YES;
[textfield setRefusesFirstResponder: YES];

【讨论】:

    【解决方案3】:

    我认为您遇到的问题与我在这里遇到的问题基本相同:pass event on。 查看接受的答案。

    按照相同的模式,您可以继承 NSTextView 并覆盖 - (void)mouseUp:(NSEvent *)theEvent 以将事件传递给 superView,我假设它是 tableView:

    - (void)mouseUp:(NSEvent *)theEvent {
        [superView mouseUp:theEvent]; 
    }
    

    【讨论】:

    • 不走运。覆盖 mouseUp: 并将事件发送到 superView 似乎没有做任何事情。然后我尝试覆盖mouseDown:并将事件发送到superView。那确实选择了行,但是我失去了选择文本的能力(基本上是文本视图的鼠标功能)。我确实按照我的回答中的描述解决了这个问题,它与你的想法并没有太大的不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 2023-03-08
    相关资源
    最近更新 更多