3
3
.
.
3
3
.
.
4
4
C
C
o
o
n
n
d
d
i
i
t
t
i
i
o
o
n
n
a
a
l
l
V
V
i
i
e
e
w
w
s
s
I
I
n
n
f
f
o
o
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.
A
A
d
d
d
d
V
V
i
i
e
e
w
w
b
b
a
a
s
s
e
e
d
d
o
o
n
n
B
B
o
o
o
o
l
l
e
e
a
a
n
n
V
V
a
a
r
r
i
i
a
a
b
b
l
l
e
e
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