我正在创建一个MacOS应用程序,希望将应用程序的状态存储在内存中,并将其传递给几个组件,但也要从这些组件更新状态.
import SwiftUI
@Observable
class Book {
var title: String
init(_ title: String) {
self.title = title
}
}
struct ParentView : View {
@State private var myBook = Book("First title")
var body: some View {
VStack {
Text("Book title (Parent): \(myBook.title)")
ChildView()
.frame(width: 200, height: 100)
.background(.teal)
.environment(myBook) // Add myBook to environment
}
}
}
struct ChildView : View {
@Environment(Book.self) var myBook: Book
var body: some View {
VStack {
Text("Book title (Child): \(myBook.title)")
TextField("Book title", text: myBook.title) // Error here!!!
}
}
}
当我试图将myBook.title
作为Binding
传递给TextField
时,这会引发错误.
Cannot convert value of type 'String' to expected argument type 'Binding<String>'
这是有道理的,但通常情况下,因为Book
是一个@Observable
类,所以我可以更新值,并让更新反映在所有用法中.
将@Observable
@Environment
类属性赋给Binding
参数的最佳方式是什么?