Sto cercando di ottenere un editor di testo avanzato per iOS in Swift che funziona, tuttavia ottengo il seguente errore:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Quando si esegue questo pezzo di codice:
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
}
}
}
L'errore appare sulla linea
if editorView.isLoading {
.
Questo è il motivo per cui suppongo che editorView non venga inizializzato, ma dovrebbe essere inizializzato come puoi vedere nel metodo 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)
}
Il metodo init non viene chiamato? O sto supervisionando qualcosa?
La classe in cui tutto questo ha la seguente firma:
public class RichTextEditor: UIView, WKScriptMessageHandler, WKNavigationDelegate, UIScrollViewDelegate {
Qualsiasi input su come posso risolvere questo problema è benvenuto! Grazie.
risposte:
0 per risposta № 1Appare che avevo due inizializzatori nel mio file e che il codice non è stato scritto per l'uso con gli storyboard. Solo il init?(coder:)
è stato chiamato quando si usano gli storyboard, quindi questo è il motivo per cui l'editorView non è stato inizializzato. Ho appena spostato tutto il codice da:
override init(frame: CGRect)
inizializzatore al
required init?(coder decoder: NSCoder)
inizializzatore e questo ha risolto il problema per me.