相关文章推荐
var body: some View { TextField("Text", text: $viewModel.text) // Cannot find '$viewModel' in scope

I found this from Bindable Document https://developer.apple.com/documentation/swiftui/bindable

thanks @macrojd

I also had that problem, this is the solution: add @Bindable var viewModel = viewModel in your view’s body, even though I don’t think it is elegant.

@Observable
final class View1Model {
  var text: String = ""
struct View1: View {
  @State var viewModel = View1Model()
  var body: some View {
    View2()
      .environment(viewModel)
struct View2: View {
  @Environment(View1Model.self) var viewModel
  var body: some View {
   // use @Bindable to get the binding  
    @Bindable var viewModel = viewModel
    TextField("Text", text: $viewModel.text) 
          

This code has good performance. But it is not cleaner than @EnvironmentObject

struct View2: View {
  @Environment(View1Model.self) var viewModel
  var body: some View {
    TextField("Text", text: Binding(get: {
      viewModel.text
    }, set: { newValue in
      viewModel.text = newValue
          

The most elegant solution I've found is to extract the view and pass the model to a @Bindable property.

@Observable
final class View1Model {
  var text: String = ""
struct View1: View {
  @State var viewModel = View1Model()
  var body: some View {
    View2()
      .environment(viewModel)
struct View2: View {
  @Environment(View1Model.self) var viewModel
  var body: some View {
    View3(viewModel: viewModel)
struct View3: View {
  @Bindable var viewModel: ViewModel
  var body: some View {
    TextField("Text", text: $viewModel.text)

I found this from Bindable Document https://developer.apple.com/documentation/swiftui/bindable

thanks @macrojd

This site contains user submitted content, comments and opinions and is for informational purposes only. Apple disclaims any and all liability for the acts, omissions and conduct of any third parties in connection with or related to your use of the site. All postings and use of the content on this site are subject to the Apple Developer Forums Participation Agreement and Apple provided code is subject to the Apple Sample Code License.
  • Forums
  • Terms of Use Privacy Policy License Agreements
     
    推荐文章