1

我已经使用 UIViewRepresentable(下面的代码)基于 UITextView 创建了一个 SwiftUI TextView。在 Swiftui 中显示文本工作正常。

但是现在我需要从我的模型中访问 UITextView 的内部函数。如何调用例如 UITextView.scrollRangeToVisible(_:) 或访问 UITextView.isEditable 之类的属性?

我的模型需要根据内部模型状态进行这些修改。

有任何想法吗 ?谢谢

(ps 我知道 SwiftUI 中的 TextEditor,但我需要对 iOS 13 的支持!)

struct TextView: UIViewRepresentable {
  @ObservedObject var config: ConfigModel = .shared
  @Binding var text: String
  
  @State var isEditable: Bool
  var borderColor: UIColor
  var borderWidth: CGFloat
  
  func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }
  
  func makeUIView(context: Context) -> UITextView {
    let myTextView = UITextView()
    myTextView.delegate = context.coordinator
    
    myTextView.isScrollEnabled = true
    myTextView.isEditable = isEditable
    myTextView.isUserInteractionEnabled = true
    myTextView.layer.borderColor = borderColor.cgColor
    myTextView.layer.borderWidth = borderWidth
    myTextView.layer.cornerRadius = 8
    return myTextView
  }
  
  func updateUIView(_ uiView: UITextView, context: Context) {
    uiView.font = uiView.font?.withSize(CGFloat(config.textsize))
    uiView.text = text
  }
  
  class Coordinator : NSObject, UITextViewDelegate {
    
    var parent: TextView
    
    init(_ uiTextView: TextView) {
      self.parent = uiTextView
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
      return true
    }
    
    func textViewDidChange(_ textView: UITextView) {
      self.parent.text = textView.text
    }
  }
}
4

1 回答 1

1

configurator您可以使用回调模式之类的东西,例如

struct TextView: UIViewRepresentable {
  @ObservedObject var config: ConfigModel = .shared
  @Binding var text: String
  
  @State var isEditable: Bool
  var borderColor: UIColor
  var borderWidth: CGFloat
  var configurator: ((UITextView) -> ())?     // << here !!

  func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }
  
  func makeUIView(context: Context) -> UITextView {
    let myTextView = UITextView()
    myTextView.delegate = context.coordinator
    
    myTextView.isScrollEnabled = true
    myTextView.isEditable = isEditable
    myTextView.isUserInteractionEnabled = true
    myTextView.layer.borderColor = borderColor.cgColor
    myTextView.layer.borderWidth = borderWidth
    myTextView.layer.cornerRadius = 8
    return myTextView
  }

  func updateUIView(_ uiView: UITextView, context: Context) {
    uiView.font = uiView.font?.withSize(CGFloat(config.textsize))
    uiView.text = text

    // alternat is to call this function in makeUIView, which is called once,
    // and the store externally to send methods directly.
    configurator?(myTextView)                  // << here !!
  }

  // ... other code
}

并在您的 SwiftUI 视图中使用它,例如

TextView(...) { uiText in
   uiText.isEditing = some
}

注意:根据您的情况,可能需要额外的条件来避免更新循环,不确定。

于 2020-12-07T12:07:50.507 回答