Created
April 3, 2021 15:44
-
-
Save koher/421aa6e8eb403da61344a578df279808 to your computer and use it in GitHub Desktop.
An example how to trigger animations with SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@StateObject private var state: ContentViewState = .init() | |
var body: some View { | |
ZStack { | |
VStack { | |
Text(state.count.description) | |
Button("Count Up") { | |
state.countUp() | |
} | |
Button("Flash") { | |
state.shouldFlash = true | |
} | |
} | |
FlashView(shouldFlash: $state.shouldFlash) | |
.ignoresSafeArea() | |
.allowsHitTesting(false) | |
} | |
} | |
} | |
final class ContentViewState: ObservableObject { | |
@Published var shouldFlash: Bool = false | |
@Published private(set) var count: Int = 0 | |
func countUp() { | |
count += 1 | |
} | |
} | |
struct FlashView: UIViewRepresentable { | |
@Binding var shouldFlash: Bool | |
func makeUIView(context: Context) -> UIView { | |
let view = UIView() | |
view.backgroundColor = .red | |
view.alpha = 0.0 | |
if shouldFlash { | |
makeViewFlash(view) | |
} | |
return view | |
} | |
func updateUIView(_ view: UIView, context: Context) { | |
if shouldFlash { | |
makeViewFlash(view) | |
} | |
} | |
private func makeViewFlash(_ view: UIView) { | |
view.alpha = 1.0 | |
UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseOut, animations: { | |
view.alpha = 0.0 | |
}) | |
shouldFlash = false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment