This tutorial shows how to programmatically include/exclude certain Views from the Screen.
This can be done using State Variable and if() {…} clause on that Variable.
We will use this approach later to demonstrate Transitions by adding and removing View from the Screen.
Initially State Variable show = false so Image View is not added to the Screen.
When we press the Button inside it's action attribute we change show to true.
Since this is a State Variable it will force SwiftUI to redraw complete View (go through its code again).
Now when SwiftUI gets to if(show) {} clause, show will be true and SwiftUI will draw Image View.
This way we have programmatically added Image View to the Screen on a click of the Button.
Example
struct ContentView: View {
//STATE VARIABLE
@State private var show = false
//BODY
var body: some View {
VStack {
Button(action: { self.show.toggle() }) { Text("BUTTON") }
if (show) { Image("Table").resizable().frame(width: 200, height: 200) }
}
}
}
Initially Image View is not shown When button is clicked Image View is added to the Screen