Swift WKWebView 未初始化并导致意外的 nil 错误



我正在尝试在Swift工作中获得iOS的丰富文本编辑器。但是,我确实会遇到以下错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

运行此代码时:

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 class RichTextEditor: UIView, WKScriptMessageHandler, WKNavigationDelegate, UIScrollViewDelegate {

欢迎有关如何解决此问题的任何输入!谢谢。

看来我的文件中有两个初始评估器,并且该代码不是为故事板使用的。仅在使用情节板时才调用init?(coder:),因此这就是未初始化EditorView的原因。我刚从:

移动了所有代码

override init(frame: CGRect)

的初始评估器

required init?(coder decoder: NSCoder)

initialiser,这解决了我的问题。

相关内容

  • 没有找到相关文章

最新更新