关闭视图swiftui时如何延迟创建动画

时间:2019-12-01 02:50:00

标签: ios swiftui

我在代码中使用了下面的示例(iOS SwiftUI: pop or dismiss view programmatically),但是我不知道如何创建动画,就像翻动页面并在点击[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()
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这将是一种方法。如果没有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)
    }
}

答案 1 :(得分:0)

您可以调度队列延迟吗?

    Button(
        "Here is Detail View. Tap to go back.",
        action: {
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
                self.presentationMode.wrappedValue.dismiss()

            }})