Home > Software design >  SwiftUI: how to make a view disappear with a slide to the top?
SwiftUI: how to make a view disappear with a slide to the top?

Time:05-17

I would like to make a view disappear with a transition to the top, but I have no idea how to do this with SwiftUI. Here is my code so far:

struct MyList: View {
    @State private var loading = true
    @State private var elements: [MyElement] = []

    var body: some View {
        ZStack {
            Color.white
            List(elements) {
                ListRow($0)
            }
            if loading {
                LoadingView() // This is the view I want to slide to the top when hiding
                    .ignoresSafeArea()
            }
        }
        .onAppear {
            callAPI() { elements in
                self.elements = elements
                self.loading = false
            }
        }
    }
}

I want to hide the LoadingView() with a slide-to-top transition, but don't know how.

Thank you for your help!

CodePudding user response:

You could use the .transition modifier.

documentation

LoadingView()
     .transition(.move(edge: .top))

But don´t forget to animate it:

.onAppear {
        self.loading = true
        callAPI() { elements in
            self.elements = elements

            DispatchQueue.main.async { // as this is probably from background Thread dispatch it
               self.loading = false
             }
        }
    }.animation(.default, value: loading)
  • Related