【问题标题】:Populating a NSImageView inside NSTouchBar在 NSTouchBar 中填充 NSImageView
【发布时间】:2017-01-16 02:58:42
【问题描述】:

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

这在我的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。现在我想使用图像/URL 在触控栏中显示相同的图像。我已经使用 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

【问题讨论】:

  • 检查 touchBarImageView 是否不是零。你不是在加载控制器之前调用 showImageInTouchBar 吗?
  • 啊,好提示!谢谢! touchBarImageView 确实为零。 但是为什么? 如果我在 MainViewController 中填充 ImageView,我不需要做任何事情。不抱歉,我在 windowDidLoad() 之后打电话给 showImageInTouchBar()。
  • 你能用你当前的代码提交到单独的分支吗?
  • 当然,我已经使用最新方法 here(提交 492f6ab)创建了一个新分支。如果您想要贡献,请随时创建拉取请求。 ;)

标签: swift macos macos-sierra nstouchbar


【解决方案1】:

我创建了一个带有修复的拉取请求。

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

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多