SwiftでiOS用のリッチテキストエディタを使用しようとしています。しかし私は、次のエラーを取得するか:Swift WKWebViewが初期化されず、予期しないnilエラーが発生する
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 {
私はこの問題を解決する方法上の任意の入力は大歓迎です!ありがとう。