Home > OS >  Can we use Bool for animatableData in SwiftUI?
Can we use Bool for animatableData in SwiftUI?

Time:01-31

I can animate my shape with updating a CGFloat value type simply, now I was looking to more reflector in my code to make it working with Bool Type as well, here what I have tried:

struct ContentView: View {
    @State private var show: Bool = true
    var body: some View {
        MyShape(show: show)
            .stroke()
            .animation(.default, value: show)
        
        Button("show") { show.toggle() }
        
    }
}

struct MyShape: Shape {
    
    var show: Bool

    var animatableData: Bool {
        get { return show }
        set(newValue) { show = newValue }
    }

    func path(in rect: CGRect) -> Path {
        return Path { path in
            path.addLines([CGPoint(x: 0, y: 100), CGPoint(x: show ? 200 : 0, y: 100)])
        }
    }
}

my working code version was using Bool value in initialization for the length of line and then my animatableData was the length of line, and that would work, as I mentioned looking to use just Bool and animate the Shape just with bool, currently my code does not animate, looking to use just Bool for making animation happen. Can we do this? or I must use a helper value type like CGFloat to translate true/false to CGFloat. But I am NOT looking for an answer using Bool and a helper value Type, I already now that way.

CodePudding user response:

You can't use Bool directly as your animatableData because Bool doesn't implement VectorArithmetic. There isn't really a sensible implementation of VectorArithmetic for Bool. How would you implement scale(by:)?

AnimatableData requires VectorArithmetic so that SwiftUI can smoothly interpolate between two values of animatableData without knowing anything else about the animatableData. There's no way to smoothly interpolate between false and true.

  •  Tags:  
  • Related