Skip to content

Instantly share code, notes, and snippets.

@programmation
Forked from chriseidhof/is_this_a_bug.swift
Last active October 9, 2021 04:27
Show Gist options
  • Save programmation/121ebcd3766f1c542b1b7751c8dbfef0 to your computer and use it in GitHub Desktop.
Save programmation/121ebcd3766f1c542b1b7751c8dbfef0 to your computer and use it in GitHub Desktop.
ZStack
import SwiftUI
struct ContentView1: View {
@State var cond = false
var body: some View {
ZStack {
Color.blue.opacity(cond ? 0.2 : 0.7)
Test(cond: cond)
}
.onTapGesture {
withAnimation(.easeInOut(duration: 1)) {
cond.toggle()
}
}
}
}
struct Test: View {
var cond: Bool
var body: some View {
VStack {
// animate properties of a single view
// SwiftUI changes text immediately and animates the color & bounds
Text(cond ? "One" : "Two")
.padding(.leading, cond ? 10 : 20)
.padding(.top, cond ? 20 : 10)
.padding(.bottom, cond ? 20 : 10)
.padding(.trailing, cond ? 10 : 20)
.background(cond ? Color.green : Color.red)
// swap views in or out of the view tree
// SwiftUI adds the view immediately and animates the
// swapped-out view's disappearance
if cond {
Text("One")
.padding(.leading, 10)
.padding(.top, 20)
.padding(.bottom, 20)
.padding(.trailing, 10)
.background(Color.green)
} else {
Text("Two")
.padding(.leading, 20)
.padding(.top, 10)
.padding(.bottom, 10)
.padding(.trailing, 20)
.background(Color.red)
}
// control view visibility through opacity
// SwiftUI fades out one view as the other is fading in
ZStack {
Text("One")
.padding(.leading, 10)
.padding(.top, 20)
.padding(.bottom, 20)
.padding(.trailing, 10)
.background(Color.green)
.opacity(cond ? 1 : 0)
Text("Two")
.padding(.leading, 20)
.padding(.top, 10)
.padding(.bottom, 10)
.padding(.trailing, 20)
.background(Color.red)
.opacity(cond ? 0 : 1)
}
}
}
}
struct ContentView1_Previews: PreviewProvider {
static var previews: some View {
ContentView1()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment