我正在尝试在 Swift 中使用适用于 iOS 的富文本编辑器。但是我确实收到以下错误:
线程 1: fatal error :在展开可选值时意外发现 nil
运行这段代码时:
public var text: String? {
didSet {
guard let text = text else { return }
if editorView.isLoading {
textToLoad = text
} else {
editorView.evaluateJavaScript("richeditor.insertText(\"\(text.htmlEscapeQuotes)\");", completionHandler: nil)
placeholderLabel.isHidden = !text.htmlToPlainText.isEmpty
}
}
}
错误出现在该行
if editorView.isLoading {
.
这就是为什么我认为 editorView 没有被初始化的原因。但是,正如您在 init 方法中看到的那样,它应该被初始化:
private var editorView: WKWebView!
public override init(frame: CGRect = .zero) {
placeholderLabel.textColor = UIColor.lightGray.withAlphaComponent(0.65)
guard let bundlePath = Bundle(for: type(of: self)).path(forResource: "Resources", ofType: "bundle"),
let bundle = Bundle(path: bundlePath),
let scriptPath = bundle.path(forResource: "RichTextEditor", ofType: "js"),
let scriptContent = try? String(contentsOfFile: scriptPath, encoding: String.Encoding.utf8),
let htmlPath = bundle.path(forResource: "RichTextEditor", ofType: "html"),
let html = try? String(contentsOfFile: htmlPath, encoding: String.Encoding.utf8)
else { fatalError("Unable to find javscript/html for text editor") }
let configuration = WKWebViewConfiguration()
configuration.userContentController.addUserScript(
WKUserScript(source: scriptContent,
injectionTime: .atDocumentEnd,
forMainFrameOnly: true
)
)
editorView = WKWebView(frame: .zero, configuration: configuration)
super.init(frame: frame)
[RichTextEditor.textDidChange, RichTextEditor.heightDidChange].forEach {
configuration.userContentController.add(WeakScriptMessageHandler(delegate: self), name: $0)
}
editorView.navigationDelegate = self
...
editorView.scrollView.delegate = self
addSubview(placeholderLabel)
...
addSubview(editorView)
editorView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([...])
editorView.loadHTMLString(html, baseURL: nil)
}
是不是没有调用init方法?还是我在监督什么?
发生这一切的类具有以下签名:
公共(public)类 RichTextEditor:UIView、WKScriptMessageHandler、WKNavigationDelegate、UIScrollViewDelegate {
欢迎就如何解决此问题提出任何意见!谢谢。
最佳答案
似乎我的文件中有两个初始化程序,并且代码不是为与 Storyboard一起使用而编写的。使用 Storyboard 时只有 init?(coder:)
被调用,所以这就是 editorView 没有被初始化的原因。我刚刚移动了所有代码:
覆盖初始化(框架:CGRect)
初始化
需要初始化吗?(编码解码器:NSCoder)
初始化程序,这为我解决了问题。
关于ios - Swift WKWebView 未初始化并导致意外的 nil 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47714326/