如何在 UIKit ViewController 中使用 EnvironmentObject

Sam*_*lki 5 uikit ios swiftui uiviewcontrollerrepresentable

我正在构建一个 SwiftUI 应用程序,ViewController通过UIViewControllerRepresentable. 目标是在我的 SwiftUI 应用程序中显示 a UITextView。这个的实现很简单,如下所示:

// iOSTextView.swift
import SwiftUI

struct iOSTextView: UIViewControllerRepresentable {
    @Binding var document: Document
    @EnvironmentObject var userData: UserData
    
    func makeUIViewController(context: Context) -> some UIViewController {
        let view = iOSTextViewController()
        return view
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {

    }
}
Run Code Online (Sandbox Code Playgroud)

注意EnvironmentObject命名的UserData. 它是一个包含一些通用数据的类,这些数据应该与我的应用程序中的每个视图共享,包括 UITextView ViewController。

// UserData.swift
import Foundation

final class UserData: ObservableObject  {
    @Published var someValue = 1
}
Run Code Online (Sandbox Code Playgroud)

下面是我的iOSTextViewController视图控制器:

// iOSTextViewController.swift
import UIKit
import SwiftUI

class iOSTextViewController: UIViewController, UIGestureRecognizerDelegate {
    @EnvironmentObject var userData: UserData

    // Create a Text View
    let textView: UITextView = {
        let tv = UITextView()
        return tv
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Place the Text View on the view
        view.addSubview(textView)
        textView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        
        // create attributed string
        let string = "This is a string."
        var attributes: [NSMutableAttributedString.Key: Any] = [
            .foregroundColor: UIColor.red,
            .font: UIFont(name: "Courier", size: 12)!
        ]
        let myAttrString = NSMutableAttributedString(string: string, attributes: attributes)
        textView.attributedText = myAttrString
    }    
}
Run Code Online (Sandbox Code Playgroud)

我的问题:

  1. 我如何传递UserData给名为 的 ViewController iOSTextViewController?我应该使用协调员吗?我如何使用它来使EnvironmentObjectViewController 内可用并同步?

  2. 同样,document由于它是基于文档的应用程序,我如何共享我的绑定?

Jor*_*n D -3

这可以在 SwiftUI 中相对轻松地完成,要将 UserData 变量传递给任何对象,您可以在单独的类中创建 Published 变量。这是一个例子

class UserDataManager: ObservableObject { 

     @Published var userData: UserData = UserData(variable1, variable2...)

}

Run Code Online (Sandbox Code Playgroud)

然后在你的视图结构中你可以简单地做

struct TextView: View { 
    
   @ObservedObject var userDataManager = UserDataManager()

   var body : some View {
     
      TextField("Enter your data", text: $userDataManager.userData.name)
Run Code Online (Sandbox Code Playgroud)