如何通过SwiftUI中的状态变量为形状设置动画?

时间:2020-02-10 15:06:44

标签: swift swiftui

在水龙头上尝试在SwiftUI中为矩形的右侧设置动画。但这不起作用( 它具有比率状态var,并且是可动画处理的类型(CGFloat)。完全出于想法为什么。请告知。

struct ContentView: View {
    @State private var animated = false

    var body: some View {
        Bar(ratio: animated ? 0.0 : 1.0).animation(Animation.easeIn(duration: 1))
        .onTapGesture {
            self.animated.toggle()
        }.foregroundColor(.green)
    }
}

struct Bar: Shape {
    @State var ratio: CGFloat

    var animatableData: CGFloat {
        get { return ratio }
        set { ratio = newValue }
    }

    func path(in rect: CGRect) -> Path {
        var p = Path()

        p.move(to: CGPoint.zero)

        let width = rect.size.width * ratio
        p.addLine(to: CGPoint(x: width, y: 0))

        let height = rect.size.height

        p.addLine(to: CGPoint(x: width, y: height))

        p.addLine(to: CGPoint(x: 0, y: height))

        p.closeSubpath()

        return p
    }
}

1 个答案:

答案 0 :(得分:1)

可动画化的数据不需要@State,因此修复很简单

struct Bar: Shape {
    var ratio: CGFloat

enter image description here

已通过此演示视图进行了测试(在Xcode 11.2 / iOS 13.2上)

struct TestAnimateBar: View {
    @State private var animated = false

    var body: some View {
        VStack {
            Bar(ratio: animated ? 0.0 : 1.0).animation(Animation.easeIn(duration: 1))
                .foregroundColor(.green)
        }
        .background(Color.gray)
        .frame(height: 40)
        .onTapGesture {
            self.animated.toggle()
        }
    }
}