4

Xcode 8.3.2 I don't find QLPreviewPanel in the command list and I don't know how to do (which command must be used) to display a file preview in a ViewController.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
eniware
  • 81
  • 2

2 Answers2

6

First of all you will need to add the import Quartz statement to your NSViewCOntroller. Second step is to add QLPreviewPanelDataSource, QLPreviewPanelDelegate to its declaration. Next you just need to get a reference of the shared QLPreviewPanel, make the view controller its dataSource and delegate and make its window key and order front.

You will need also to add numberOfPreviewItems and previewItemAt methods to your controller. You can do it as follow:

import Quartz

class ViewController: NSViewController,  QLPreviewPanelDataSource, QLPreviewPanelDelegate {

    @IBAction func button(_ sender: NSButton) {
        if let sharedPanel = QLPreviewPanel.shared() {
            sharedPanel.delegate = self
            sharedPanel.dataSource = self
            sharedPanel.makeKeyAndOrderFront(self)
        }
    }

    func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int {
        return 1
    }

    func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> QLPreviewItem! {
        let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("yourImageAtTheDocs.png")
        return url as QLPreviewItem
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Thank you for help. I inserted : import Cocoa import QuickLook import Quartz and than class ViewController: NSViewController, NSCollectionViewDelegate,NSCollectionViewDataSource, QLPreviewPanelDataSource, QLPreviewPanelDelegate {.... and other instructions. I have a button made to invoke the preview. This button open a new view controller, called SecondViewController and present in main storyboard, in show mode. Do I need to insert code in SecondViewController.swift? – eniware May 10 '17 at 09:31
0

Sadly Apples QuickLookDownloader Demo uses Obj-C. I've created a Swift Versiob which is basically the implementation of @Leo Dabus answer in a Demo Project: Panel and Popover example

Deitsch
  • 1,610
  • 14
  • 28