DEV Community

Cover image for count increasing text
Rubydog
Rubydog

Posted on

count increasing text

Hello, great hackers. I'm a Japanese dog.

Please use my trivial "AnimationReader" to animate text, with dinamic number.

such as increasing count, or to control state of somethting.

ContentView.swift

Sample


import SwiftUI
struct ContentView: View {
    @State var count: Int = 0
    var body: some View {

        // observe count
        AnimationReader(count) { value in
            // use value instead of raw count
            Text("total: \(value)")
        }

        // test
        .onAppear {
            withAnimation(.easeInOut(duration: 10)) {
                count += 99
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

AnimationReader.swift


import SwiftUI

fileprivate struct AnimationReaderModifier<Body: View>: AnimatableModifier {
    let content: (CGFloat) -> Body
    var animatableData: CGFloat

    init(value: CGFloat, @ViewBuilder content: @escaping (CGFloat) -> Body) {
        self.animatableData = value
        self.content = content
    }

    func body(content: Content) -> Body {
        self.content(animatableData)
    }
}

struct AnimationReader<Content: View>: View {

    let value: CGFloat
    let content: (_ animatingValue: CGFloat) -> Content

    init(_ observedValue: Int, @ViewBuilder content: @escaping (_ animatingValue: Int) -> Content) {
        self.value = CGFloat(observedValue)
        self.content = { value in content(Int(value)) }
    }

    init(_ observedValue: CGFloat, @ViewBuilder content: @escaping (_ animatingValue: CGFloat) -> Content) {
        self.value = observedValue
        self.content = content
    }

    var body: some View {
        EmptyView()
            .modifier(AnimationReaderModifier(value: value, content: content))
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks to read

Top comments (0)