NSAnimationContext在被Observer调用时崩溃



我有两个WebViews:webViewcustomizerWebView。这两个WKWebView都通过一个尾随约束附加。本质上,当我转到菜单并单击"显示自定义程序"showCustomizer()或"隐藏自定义程序"hideCustomizer()时,它会调用相应的函数,并显示或隐藏与customizerWebView相关的所有内容。

需要说明的是,当从所附的NSMenuItems调用这些函数时,一切都按预期工作并设置动画然而,show/hideCustomizer()从一个基本上检测到URL的Observer调用时,即url.contains("#close"),应用程序在animator()代码的第一行崩溃,并出现错误:Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

ViewController.swift

import Cocoa
import WebKit
class ViewController: NSViewController, WKUIDelegate, WKNavigationDelegate {
var customizerURLObserver: NSKeyValueObservation?
@IBOutlet var webView: WKWebView!
@IBOutlet var customizerWebView: WKWebView!
@IBOutlet var rightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad
...
customizerURLObserver = customizerWebView.observe(.url, options: .new) { webView, change in
let url = "(String(describing: change.newValue))"
ViewController().urlDidChange(urlString: url) }
}
func urlDidChange(urlString: String) {
let url = cleanURL(urlString)
if url.contains("#close") { hideCustomizer() }  // Observer call to hide function
}
@IBAction func showCustomizerMenu(_ sender: Any) { showCustomizer() }  // These work flawlessly
@IBAction func hideCustomizerMenu(_ sender: Any) { hideCustomizer() }  // These work flawlessly
func showCustomizer() {
let customTimeFunction = CAMediaTimingFunction(controlPoints: 5/6, 0.2, 2/6, 0.9)
NSAnimationContext.runAnimationGroup({(_ context: NSAnimationContext) -> Void in
context.timingFunction = customTimeFunction
context.duration = 0.3
rightConstraint.animator().constant = 280
customizerWebView.animator().isHidden = false
webView.animator().alphaValue = 0.6
}, completionHandler: {() -> Void in
})
}
func hideCustomizer() {
let customTimeFunction = CAMediaTimingFunction(controlPoints: 5/6, 0.2, 2/6, 0.9)
NSAnimationContext.runAnimationGroup({(_ context: NSAnimationContext) -> Void in
context.timingFunction = customTimeFunction
context.duration = 0.3
webView.animator().alphaValue = 1     // Found nil crash highlights this line
rightConstraint.animator().constant = 0
}, completionHandler: {() -> Void in
self.customizerWebView.isHidden = true
})
}
}

有人能告诉我,为什么这个动画在从NSMenu调用100次时看起来和工作都很完美,但在从Observer函数调用hideCustomizer()一次时崩溃?

我也尝试过调用NSMenu对象函数hideCustomizerMenu(self),但没有成功。

在线:

ViewController().urlDidChange(urlString: url)

您错误地创建了视图控制器类的新实例,并在实例上调用urlDidChange。由于这个新实例不是从故事板/xib创建的,所以它的所有出口都是nil,因此当您尝试在hideCustomizer中的webView上调用animator方法时,它会崩溃,因为它是nil。

相反,在self上调用urlDidChange(实际上是一个弱化的self,这样就不会创建保留循环(:

customizerURLObserver = customizerWebView.observe(.url, options: .new) { [weak self] webView, change in
let url = "(String(describing: change.newValue))"
self?.urlDidChange(urlString: url)
}

相关内容

  • 没有找到相关文章

最新更新