在 NSTouchBar 中填充一个 NSImageView

Populating a NSImageView inside NSTouchBar

我目前正在创建一个微型 open source app 来预览新 Touch Bar 的内部。 我有一个带有拖放视图的 window,可以通过它的 URL 接收图像。以及在 TouchBarView 中带有 NSImageView 的 IB Touch Bar。
interface builder structure (screenshot)

这在我的 MainViewController 中有效以显示 window 中的图像:

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。现在我想使用 image/URL 在 Touch Bar 中显示相同的图像。我已经使用 Interface Builder 创建了 Touch Bar,并将图像-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
        }
    }
}

我通过 print(url) 收到了正确的 URL,但是当我再次尝试创建图像时,应用程序崩溃并显示以下消息:

fatal error: unexpectedly found nil while unwrapping an Optional value

我创建了一个包含修复的拉取请求。

您的问题是您正在创建一个新的 WindowController 并将其用作参考,而不是使用由 NSWindow 创建和使用的控制器。

结果: