带有UIViewcontrollerRepresentable的自定义UIViewController,其UITextView在SwiftUI中调用时崩溃或为零

时间:2020-06-17 06:21:29

标签: swiftui nsattributedstring uiviewcontrollerrepresentable

我制作了一个名为UIViewController的自定义ViewControllerA,并希望能够使用它,因此我制作了一个名为UIViewControllerRepresentable的{​​{1}},如下所示,但问题是当我在SwiftUI视图中调用ViewControllerARepresentable并传递ViewControllerARepresentable的值时,stringToUpdateTextViewViewControllerA中的htmlTextView(UITextView)ViewControllerA,我不确定为什么。

nil

ViewControllerARepresentable

ViewControllerARepresentable(stringToUpdateTextView: "<html>Send some Html Text as string here</html>")

ViewControllerA

public struct ViewControllerARepresentable: UIViewControllerRepresentable {
  var stringToUpdateTextView: String

  public func makeUIViewController(context: Context) -> ViewControllerA {
    let viewcontrollerA = ViewControllerA(testString: testingString)

    return viewcontrollerA
  }

  public func updateUIViewController(_ uiViewController: ViewControllerA, context: Context) {}
}

崩溃发生在open class ViewControllerA: UIViewController { public var stringToUpdateTextView: String override open func viewDidLoad() { super.viewDidLoad() htmlTextView.text = stringToUpdateTextView } @IBOutlet weak var htmlTextView: UITextView! public init(testString: String) { self.testString = testString super.init(nibName: nil, bundle: nil) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } ,说htmlTextView.text为零,即使它是IBOutlet也是如此。 对htmlTextView所做的任何更改(例如背景色等),如果在viewDidAppear或viewDidLoad中调用

,也会导致崩溃

1 个答案:

答案 0 :(得分:2)

makeUIViewController中实例化视图控制器时,出口尚未初始化。

以下代码从情节提要中加载视图控制器,并更新updateUIViewController中的属性:

ViewController.swift

import UIKit
import SwiftUI

class ViewController: UIViewController {

  @IBOutlet weak var htmlTextView: UITextView!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
  }

}

struct ViewControllerWrapper: UIViewControllerRepresentable {
  typealias UIViewControllerType = ViewController

  @Binding var text: String

  func makeUIViewController(context: Context) -> ViewController {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let viewController =  storyboard.instantiateViewController(
      identifier: "ViewController") as? ViewController else {
        fatalError("Cannot load from storyboard")
    }
    return viewController
  }

  func updateUIViewController(_ uiViewController: ViewController, context: Context) {
    uiViewController.htmlTextView.text = text
  }

}


struct ViewControllerPreview: PreviewProvider {
  static var previews: some View {
    ViewControllerWrapper(text: .constant("hello world!"))
  }
}

SwiftUIView.swift

struct SwiftUIView: View {
  @State var text = "Text"
  var body: some View {
    HStack {
      TextField("Text:", text: $text)
      ViewControllerWrapper(text: $text)
    }
  }
}