我试图在ZStack中创建多个转换。
这是一个包含一些文本和一个圆圈的测试视图,它们都有自己的转换。

struct Test: View {
    @Binding var isPresented: Bool
    @State private var showCircle: Bool = false
    @State private var showRect: Bool = false

    var body: some View {
        ZStack {
             if showRect {
                 VStack {
                     Text("Hello World")
                         .foregroundColor(.white)
                         .padding()
                 }
                 .background(Color.green)
                 .transition(.move(edge: .bottom))
            }

            if showCircle {
                Circle()
                    .fill(Color.purple)
                    .transition(.slide)
            }
        }
        .onAppear() {
            withAnimation {
                self.showRect.toggle()
                self.showCircle.toggle()
            }
        }
        .onDisappear() {
            withAnimation {
                self.showCircle.toggle()
                self.showRect.toggle()
            }
        }
    }
}

我这样添加这个视图:
struct ContentView: View {
    @State private var toggler: Bool = false

    var body: some View {
        ZStack {

            if toggler {
                Test(isPresented: $toggler)
            }

            Button("Show/Hide") {
                withAnimation {
                    self.toggler.toggle()
                }
            }
        }
    }
}

这些转变在表面上起作用。
但是onDisappear似乎是在搬家的时候被叫来的,而不是之前。
如何重置状态变量以触发移除时的转换,或者应该使用什么其他方法?
其他尝试:
我还尝试创建自定义修饰符以将其与Anytransition.modifier一起使用,但失败,因为我无法通过类型转换访问状态变量,Anytransition.modifier要求修饰符符合ViewModifier。
在TestView中的dissive函数,如果我想将视图从自身中删除,它就可以工作,但是当它被其父级删除时,显然不行。

最佳答案

这样做,而不是突然消失

struct ContentView : View {
    @State private var isButtonVisible = true

    var body: some View {
        VStack {
            Toggle(isOn: $isButtonVisible.animation()) {
                Text("Show/Hide button")
            }

            if isButtonVisible {
                Button(action: {}) {
                    Text("Hidden Button")
                }.transition(.move(edge: .trailing))
            }
        }
    }
}

或者用按钮
struct ContentView : View {
    @State private var isButtonVisible = true

    var body: some View {
        VStack {
            Button(action: {
                withAnimation {
                    self.isButtonVisible.toggle()
                }
            }) {
                Text("Press me")
            }

            if isButtonVisible {
                Button(action: {}) {
                    Text("Hidden Button")
                }.transition(.move(edge: .trailing))
            }
        }
    }
}

您还可以合并转换:请查看:https://swiftwithmajid.com/2019/06/26/animations-in-swiftui/

10-07 16:37