双击NSCollectionView

时间:2013-01-29 01:42:57

标签: cocoa nscollectionview

我正在尝试让我的程序识别出使用NSCollectionView双击。我已经尝试过遵循本指南:http://www.springenwerk.com/2009/12/double-click-and-nscollectionview.html但是当我这样做时,没有任何反应,因为IconViewBox中的委托是null:

h文件:

@interface IconViewBox : NSBox
{
    IBOutlet id delegate;
}
@end

m文件:

@implementation IconViewBox

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

    // check for click count above one, which we assume means it's a double click
    if([theEvent clickCount] > 1) {
        NSLog(@"double click!");
        if(delegate && [delegate respondsToSelector:@selector(doubleClick:)]) {
            NSLog(@"Runs through here");
            [delegate performSelector:@selector(doubleClick:) withObject:self];
        }
    }
}

第二个NSLog永远不会被打印,因为委托为空。我已经连接了我的nib文件中的所有内容并按照说明操作。有谁知道为什么或替代为什么这样做?

3 个答案:

答案 0 :(得分:5)

您可以通过继承集合项的视图来捕获集合视图项中的多次单击。

  1. 子类NSView并添加mouseDown:方法以检测多次点击
  2. 将nib中的NSCollectionItem视图从NSView更改为MyCollectionView
  3. 在关联的collectionItemViewDoubleClick:
  4. 中实施NSWindowController

    这可以让NSView子类检测到双击并传递响应者链。调用响应者链中实现collectionItemViewDoubleClick:的第一个对象。

    通常,您应该在关联的collectionItemViewDoubleClick:中实现NSWindowController,但它可以位于响应者链中的任何对象中。

    @interface MyCollectionView : NSView
    /** Capture double-clicks and pass up responder chain */
    -(void)mouseDown:(NSEvent *)theEvent;
    @end
    
    @implementation MyCollectionView
    
    -(void)mouseDown:(NSEvent *)theEvent
    {
        [super mouseDown:theEvent];
    
        if (theEvent.clickCount > 1)
        {
            [NSApplication.sharedApplication sendAction:@selector(collectionItemViewDoubleClick:) to:nil from:self];
        }
    }
    
    @end
    

答案 1 :(得分:0)

尽管如此,您需要确保遵循教程中的第四步:

4. Open IconViewPrototype.xib in IB and connect the View's delegate outlet with "File's Owner":

如果您按照其他步骤进行操作,那应该这样做。

答案 2 :(得分:0)

另一种选择是覆盖NSCollectionViewItem并添加一个NSClickGestureRecognizer,如下所示:

- (void)viewDidLoad
{
    NSClickGestureRecognizer *doubleClickGesture = 
            [NSClickGestureRecognizer alloc] initWithTarget:self
                                                     action:@selector(onDoubleClick:)];
   [doubleClickGesture setNumberOfClicksRequired:2];
   // this should be the default, but without setting it, single clicks were delayed until the double click timed-out
   [doubleClickGesture setDelaysPrimaryMouseButtonEvents:FALSE];
   [self.view addGestureRecognizer:doubleClickGesture];
}

- (void)onDoubleClick:(NSGestureRecognizer *)sender
{
    // by sending the action to nil, it is passed through the first responder chain
    // to the first object that implements collectionItemViewDoubleClick:
    [NSApp sendAction:@selector(collectionItemViewDoubleClick:) to:nil from:self];
}