2017-12-08 3 views
0

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 {

나는이 문제를 해결할 수있는 방법에 대한 입력을 환영합니다! 감사.

답변

0

내 파일에 두 개의 초기화 프로그램이 있으며 코드가 스토리 보드와 함께 사용하도록 작성되지 않은 것으로 나타납니다. 스토리 보드를 사용할 때는 init?(coder:) 만 호출되었으므로 editorView가 초기화되지 않았습니다.

required init?(coder decoder: NSCoder)

initialiser에

override init(frame: CGRect)

initialiser이 나를 위해 문제를 해결 : 난 그냥 모든 코드를 이동했다.