I ran into an issue when using the @State property.
My ContentView.swift looks like this:
import SwiftUI
struct ContentView: View {
@State var showText: Bool = true
var Mod: Modifier
init() {
Mod = Modifier(showText: $showText) // Throws error -> 'self' used before all stored properties are initialized ('self.Mod' not initialized)
}
var body: some View {
VStack {
if showText == true {
Text("Hello, World!")
}
Mod
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
And my Modifier.swift from which the Modifier view is called has following code:
import SwiftUI
struct Modifier: View {
@Binding var showText: Bool
var body: some View {
VStack {
Button("Hide Text") {
self.showText.toggle()
}
}
}
}
I created this simplified code from my actual project that my problem is easier to understand.
Problem
The problem is that the code in the init function results into an error and I don't know how to resolve it.
What I tried and what I would need
Because this is just a simplified version of my actual code there are some requirements I need to my code:
- Mod can't be a computed variable
- I somehow need the
Modifier
view as a variable calledMod
in my ContentView - When I remove the
@State
property and the@Binding
property and the$
the code works and results with 0 errors. But I need to use the@State
property (which unfortunately results into errors with my code) - Also the button to hide and show the text should work
I would be very thankful if anyone could give me a hint. I really appreciate your help!