swiftui alert Cannot use instance member '$text' with in property initializer; property initializers run before 'self' is available

Asked 1 years ago, Updated 1 years ago, 267 views

In swiftui

Trying to instantiate TextEditor

Cannot use instance member '$text' with in property initializer; property initializers run before 'self' is available

The alert appears.

let textEditor=TextEditor(text:$text)

says .

swift

2022-11-11 02:23

1 Answers

There are some problems, so I will raise them.

I think the code is probably like this.

struct ContentView:View {
  @State var text: String="Hello"
  
  let textEditor=TextEditor(text:$text)//Cannot use instance member '$text' with in property initializer; property initializers run before 'self' is available
  
  varbody:someView {
    textEditor
  }
}

Make it Computed Property

struct ContentView:View {
  @State var text: String="Hello"
  
  vartextEditor: TextEditor {TextEditor(text:$text)}
  
  varbody:someView {
    textEditor
  }
}

This is an example of a school or way of thinking, so it's not absolutely true.

When you want to start a View, you choose to make it variable or structured, so you only need to preview it.
If you don't need Preview, choose structure.

The following are helpful:

https://speakerdeck.com/uhooi/iosdc-japan-2022

If you want to customize TextEditor relatively complexly, cut it into a separate structure.

Otherwise, I will use it directly in the body.

Example 1

struct ContentView:View {
  @State var text: String="Hello"
  
  varbody:someView {
    TextEditor (text:$text)
  }
}

Example 2

struct ContentView:View {
  @State var text: String="Hello"
  
  varbody:someView {
    VStack {
      RichTextEditor (text:$text)
    }
  }
}

structure RichTextEditor:View {
  @Binding var text: String
  
  varbody:someView {
    VStack {
      Text ("Editor")
        .padding()
        .border (.blue)
        .padding()
      
      TextEditor (text:$text)
    }
    .border (.red, width:5)
  }
}


2022-11-11 03:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.