我正在构建一个SwiftUI应用程序,它将UIKitViewController
封装到UIViewControllerRepresentable
。目标是在我的SwiftUI应用程序中显示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) {
}
}
请注意名为UserData
的EnvironmentObject
。它是一个类,包含一些通用数据,应该与我的应用程序中的每个视图共享,包括UITextView ViewController。
// UserData.swift
import Foundation
final class UserData: ObservableObject {
@Published var someValue = 1
}
下面是我的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
}
}
我的问题:
如何将
UserData
传递给名为iOSTextViewController
的ViewController?我应该使用协调员吗?如何使用它使EnvironmentObject
在ViewController中可用并同步?同样,既然
document
绑定是一个基于文档的应用程序,我该如何共享它呢?
这可以在SwiftUI中相对容易地完成,将UserData变量传递给任何对象,您可以在单独的类中创建Published变量。以下是的示例
class UserDataManager: ObservableObject {
@Published var userData: UserData = UserData(variable1, variable2...)
}
然后在您的View结构中,您可以简单地执行
struct TextView: View {
@ObservedObject var userDataManager = UserDataManager()
var body : some View {
TextField("Enter your data", text: $userDataManager.userData.name)