swiftui, animation applied to parent effect child animation(Part II)

家住魔仙堡 提交于 2021-01-29 17:25:45

问题


PREVIOUS Q: swiftui, animation applied to parent effect child animation

Now the TextView has its own state. RectangleView with TextView slide into screen in 3 seconds, but state of TextView changed after a second while sliding. Now you can see TextView stops sliding, go to the destination at once. I Just want RectangleView with TextView as a whole when sliding, and TextView rotates or keeps still as I want.

import SwiftUI

struct RotationEnvironmentKey: EnvironmentKey {
    static let defaultValue: Bool = false
}

extension EnvironmentValues {
    var rotation: Bool {
        get { return self[RotationEnvironmentKey] }
        set { self[RotationEnvironmentKey] = newValue }
    }
}

struct AnimationTestView: View {
    @State private var go = false
    @State private var rotation = false
    var body: some View {
        VStack {
            Button("Go!") {
                go.toggle()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                    rotation.toggle()
                    print("set rotation = \(rotation)")
                }
            }
            Group {
                if go {
                    RectangleView()
                        .transition(.slide)
                        .environment(\.rotation, rotation)
                }
            }.animation(.easeInOut(duration: 3.0), value: go)
        }.navigationTitle("Animation Test")
    }
}

struct RectangleView: View {
    var body: some View {
        Rectangle()
            .frame(width: 200, height: 100)
            .foregroundColor(.pink)
            .overlay(TextView())
    }
}

struct TextView: View {
    @Environment(\.rotation) var rotation
    @State private var animationRotating: Bool = false
    let animation = Animation.linear(duration: 3.0).repeatForever(autoreverses: false)
    
    var body: some View {
        print("refresh, rotation = \(rotation)"); return
        HStack {
            Spacer()
            if rotation {
                Text("R")
                    .foregroundColor(.blue)
                    .rotationEffect(.degrees(animationRotating ? 360 : 0))
                    .animation(animation, value: animationRotating)
                    .onAppear { animationRotating = true }
                    .onDisappear { animationRotating = false }
            } else {
                Text("S")
            }
        }
    }
}

来源:https://stackoverflow.com/questions/65614683/swiftui-animation-applied-to-parent-effect-child-animationpart-ii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!