Search code examples
objective-cmacoscocoanscollectionviewquicklook

How to use SpaceBar button inside an application to invoke quick look


i had displayed some images in collectionview. now i want to select the image and press space button. If i pressed Space button , the image should quicklook in a seperate window. any idea?


Solution

  • On your view, do this:

    - (void)keyDown:(NSEvent *)event
    {
      unichar firstChar = 0;
      if ([[event charactersIgnoringModifiers] length] > 0)
        firstChar = [[event charactersIgnoringModifiers] characterAtIndex:0];
    
      if (firstChar == ' ')
      {
        if ([QLPreviewPanel sharedPreviewPanelExists]
            && [[QLPreviewPanel sharedPreviewPanel] isVisible])
        {
          [[QLPreviewPanel sharedPreviewPanel] orderOut:nil];
        }
        else
        {
          [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
          [[NSApp mainWindow] makeKeyWindow];
        }
      }
      else if (firstChar == NSRightArrowFunctionKey)
      {
        if ([QLPreviewPanel sharedPreviewPanelExists]
            && [[QLPreviewPanel sharedPreviewPanel] isVisible])
        {
          [[QLPreviewPanel sharedPreviewPanel] selectNextItem];
          return;
        }
      }
      else if (firstChar == NSLeftArrowFunctionKey)
      {
        if ([QLPreviewPanel sharedPreviewPanelExists]
            && [[QLPreviewPanel sharedPreviewPanel] isVisible])
        {
          [[QLPreviewPanel sharedPreviewPanel] selectPreviousItem];
          return;
        }
      }
      else
        [super keyDown:event];
    }
    

    Then, I do this in my app's delegate (AppDelegate.m):

    - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel *)panel
    {
      //note that this methods indeed gets called because NSApp's
      //delegate is in the responder chain.
      return YES;
    }
    
    - (void)beginPreviewPanelControl:(QLPreviewPanel *)panel
    {
      previewPanel = panel; //set an ivar
      [panel setDataSource:self];
    }
    
    - (void)endPreviewPanelControl:(QLPreviewPanel *)panel
    {
      previewPanel = nil;
    }
    
    - (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel *)panel
    {
      //return a number of your choice (depends on your own app)
    }
    
    - (id <QLPreviewItem>)previewPanel:(QLPreviewPanel *)panel
                    previewItemAtIndex:(NSInteger)index
    {
      //return an object of your choice (depends on your app)
    }
    
    - (void)handleCurrentFileItemsSelectionChange:(NSNotification *)note
    {
      [previewPanel reloadData]; //referring to the ivar
    }