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 {
나는이 문제를 해결할 수있는 방법에 대한 입력을 환영합니다! 감사.