我有两个 WebView:webView
和customizerWebView
. 这两个 WKWebViews 都由一个尾随约束附加。本质上,当我转到菜单并单击“显示定制器”showCustomizer()
或“隐藏定制器”hideCustomizer()
时,它会调用相应的函数并显示或隐藏与customizerWebView
.
澄清一下,当从附加的NSMenuItems
. 但是,当show/hideCustomizer()
从本质上检测 URL 的观察者调用时 - 即。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 次,但在hideCustomizer()
从观察者函数调用一次时崩溃?
我也尝试过调用 NSMenu 对象函数hideCustomizerMenu(self)
,但无济于事。