Created
March 20, 2024 13:56
-
-
Save kirti-swiggy/d396cb401a56923efc4c0ebeeded8223 to your computer and use it in GitHub Desktop.
Counter animation. Demo: https://imgur.com/a/3tEx6B9
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 | |
import PlaygroundSupport | |
struct ContentView: View { | |
@State var number: Int = 1 | |
@State var dummyFlag: Bool = true | |
@State var isIncrement: Bool = false // forgive me for this, this is just for demonstration. Surely there are better ways | |
var body: some View { | |
Rectangle() | |
.frame(width: 300, height: 50) | |
.foregroundColor(.white) | |
.overlay { | |
HStack { | |
Text("-") | |
.foregroundColor(.red) | |
.onTapGesture { | |
isIncrement = false | |
withAnimation(.easeInOut(duration: 0.2)) { | |
dummyFlag.toggle() | |
} | |
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: { | |
number -= 1 | |
}) | |
} | |
textView | |
Text("+") | |
.foregroundColor(.blue) | |
.onTapGesture { | |
isIncrement = true | |
withAnimation(.easeInOut(duration: 0.2)) { | |
dummyFlag.toggle() | |
} | |
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: { | |
number += 1 | |
}) | |
} | |
} | |
} | |
} | |
@ViewBuilder | |
private var textView: some View { | |
Group { | |
if dummyFlag { | |
Text("\(number)") | |
} else { | |
Text("\(number)") | |
} | |
} | |
.monospaced() | |
.frame(maxHeight: .infinity) | |
.transition(.asymmetric(insertion: isIncrement ? .push(from: .bottom) : .push(from: .top), removal: isIncrement ? .move(edge: .top) : .move(edge: .bottom))) | |
} | |
} | |
PlaygroundPage.current.setLiveView(ContentView()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment