SwiftUI likes knowing what type of view is going to be rendered.
Most views are hardcoded and there don’t change dynamically. However, if you need to show other views because some parameter changes it isn’t possible as you might think in the first second. The code like this doesn’t work:
if Bool.random() {
TextField(“Write something”, text: self.$inputText)
} else {
Text(“Sorry, you can’t write anymore”)
}
There are two ways to make this code work.
The first one is to embed a view inside the AnyView.
if Bool.random() {
return AnyView(TextField(“Write something”, text: self.$inputText))
} else {
return AnyView(Text(“Sorry, you can’t write anymore”))
}
Another option is to embed views inside the Group view. It’s the same view as it’s used to bypass 10 view limits.
Group {
if Bool.random() {
TextField(“Write something”, text: self.$inputText)
} else {
Text(“Sorry, you can’t write anymore”)
}
}
inputText is a simple State property.
@State private var inputText = “”