swiftui, animation applied to parent effect child animation

后端 未结 1 1506
悲&欢浪女
悲&欢浪女 2021-01-21 07:36

RectangleView has a slide animation, his child TextView has a rotation animation. I suppose that RectangleView with his child(TextView) as a whole slide(easeInOut) into screen w

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-21 08:23

    If there are several simultaneous animations the generic solution (in majority of cases) is to use explicit state value for each.

    So here is a corrected code (tested with Xcode 12.1 / iOS 14.1, use Simulator or Device, Preview renders some transitions incorrectly)

    struct AnimationTestView: View {
        @State private var go = false
        var body: some View {
            VStack {
                Button("Go!") {
                    go.toggle()
                }
                    VStack {      // container needed for correct transition !!
                        if go {
                             RectangleView()
                                  .transition(.slide)
                        }
                    }.animation(.easeInOut, value: go)    // << here !!
            }.navigationTitle("Animation Test")
        }
    }
    
    struct RectangleView: View {
        var body: some View {
            Rectangle()
                .frame(width: 100, height: 100)
                .foregroundColor(.pink)
                .overlay(TextView())
        }
    }
    
    struct TextView: View {
        @State private var animationRotating: Bool = false
        let animation = Animation.linear(duration: 3.0).repeatForever(autoreverses: false)
        
        var body: some View {
            Text("Test")
                .foregroundColor(.blue)
                .rotationEffect(.degrees(animationRotating ? 360 : 0))
                .animation(animation, value: animationRotating)          // << here !!
                .onAppear { animationRotating = true }
                .onDisappear { animationRotating = false }
        }
    }
    

    0 讨论(0)
提交回复
热议问题