Skip to content

Instantly share code, notes, and snippets.

@magnuskahr
Created May 13, 2021 21:21
Show Gist options
  • Save magnuskahr/e2055cfec063b1e2b7d30e6409aed311 to your computer and use it in GitHub Desktop.
Save magnuskahr/e2055cfec063b1e2b7d30e6409aed311 to your computer and use it in GitHub Desktop.
Rolling animatable view
struct AnimateableView<ContentView: View, Value: VectorArithmetic>: View {
let value: Value
@ViewBuilder let builder: (Value) -> ContentView
var body: some View {
builder(value)
.modifier(Animation<ContentView, Value>(value: value, builder: builder))
}
private struct Animation<ContentView: View, Value: VectorArithmetic>: AnimatableModifier {
var value: Value
@ViewBuilder let builder: (Value) -> ContentView
var animatableData: Value {
get { value }
set { value = newValue }
}
func body(content: Content) -> some View {
builder(value)
}
}
}
extension AnimateableView {
init(_ value: Value, @ViewBuilder builder: @escaping (Value) -> ContentView) {
self.value = value
self.builder = builder
}
}
extension AnimateableView where Value: CustomStringConvertible, ContentView == Text {
init(_ value: Value) {
self.init(value: value) {
Text($0.description)
}
}
}
@magnuskahr
Copy link
Author

Usage:

struct Demo: View {
        
        @State var test = 0.0
        
        var body: some View {
            VStack {
                AnimateableView(value: test) {
                    Text(String(Int($0)))
                }
                .animation(.easeIn, value: test)
                
                Button("Add 5") {
                    test += 5
                }
            }
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment