2017-01-15 28 views
0

我目前正在創建一個小巧的open source app來預覽新的Touch Bar的內部。 我有一個拖放n拖放視圖的窗口,通過它的URL接收圖像。並且在TouchBarView中有一個帶有NSImageView的IB Touch Bar。
interface builder structure (screenshot)在NSTouchBar內部填充一個NSImageView

這是工作在我MainViewController顯示在窗口中的圖像:

extension ViewController: DropDestinationViewDelegate { 

    func processImageURLs(_ urls: [URL]) { 
     for (_,url) in urls.enumerated() { 

      // pass URL to Window Controller 
      let windowController = WindowController() 
      windowController.showImageInTouchBar(url) 

      // create the image from the content URL 
      if let image = NSImage(contentsOf:url) { 

       imagePreviewView.image = image 
      } 
     } 
    } 

} 

正如你可以看到我使用委託聽拖動ñ丟棄事件來獲得圖像URL。現在我想使用圖片/網址在觸摸欄中顯示相同的圖片。我已經使用Interface Builder創建了觸摸條,並將圖像url傳遞給WindowController

在我WindowController我嘗試處理這樣的形象:

class WindowController: NSWindowController { 

    @IBOutlet var touchBarImageView: NSImageView! 

    override func windowDidLoad() { 
     super.windowDidLoad() 
    } 

    func showImageInTouchBar(_ url: URL) { 
     print(url) 

     if let touchbarImage = NSImage(contentsOf:url) { 
      touchBarImageView.image = touchbarImage 
     } 
    } 
} 

我收到了正確的URL與print(url),但是當我再次嘗試創建圖像,應用程序與下面的崩潰消息:

fatal error: unexpectedly found nil while unwrapping an Optional value 
+0

檢查_touchBarImageView_不是零。你不是在控制器加載之前調用_showImageInTouchBar_嗎? –

+0

啊好暗示!謝謝! 'touchBarImageView'實際上是零。 **但爲什麼?**如果我在我的'MainViewController'中填充ImageView,我不需要做任何事情。沒有抱歉,我在'windowDidLoad()'之後調用'showImageInTouchBar()'。 – alexkaessner

+0

你可以用你當前的代碼進行提交以分離分支嗎? –

回答

0

我創建了一個修復拉請求。

你的問題是,你是創建一個新的WindowController並以此作爲參考,而不是使用NSWindow創建和使用的控制器。

結果:

enter image description here