首页 > 解决方案 > 如何在关闭视图swiftui时延迟创建动画

问题描述

我在我的代码中使用了以下示例(iOS SwiftUI:以编程方式弹出或关闭视图),但我不知道如何创建动画,就像翻页一样,并在点击 [Button] 时延迟几秒钟。有谁知道解决方案?

struct DetailView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    var body: some View {
        Button(
            "Here is Detail View. Tap to go back.",
            action: {

                //withAnimation(.linear(duration: 5).delay(5))// Error occurred in dalay.(Type of expression is ambiguous without more context)
                withAnimation(.linear(duration: 5)) // not work 
                {
                    self.presentationMode.wrappedValue.dismiss()
                }
        }
        )
    }
}

struct RootView: View {
    var body: some View {
        VStack {
            NavigationLink(destination: DetailView())
            { Text("I am Root. Tap for Detail View.")
        }
    }
}

struct ContentView: View {
    var body: some View {
        NavigationView {
            RootView()
        }
    }
}

标签: iosswiftui

解决方案


这将是一种方法。如果没有,NavigationLink您可以完全控制所有动画和过渡。

struct DetailView: View {
    @Binding var showDetail:Bool

    var body: some View {
        Button(
            "Here is Detail View. Tap to go back.",
            action: {
                withAnimation(Animation.linear.delay(2)){
                    self.showDetail = false
                }
            }
        ).frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.yellow)
    }
}

struct RootView: View {
    @State var showDetail = false

    var body: some View {
        VStack {
            if showDetail{
                DetailView(showDetail:self.$showDetail).transition(.move(edge: .trailing))
            }else{
                Button("I am Root. Tap for Detail View."){
                    withAnimation(.linear){
                        self.showDetail = true
                    }
                }
            }
        }.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.red)
    }
}


推荐阅读