【发布时间】: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()。 -
你能用你当前的代码提交到单独的分支吗?
标签: swift macos macos-sierra nstouchbar