Search code examples
swiftuidelay

SwiftUI show custom View with delay


I have something like this in my ZStack :

if hidePopup {
      CustomButton()
      .hidden()
 } else if stateManager.isBtnClosePressed {
      CustomButton()
      .hidden()
 } else {
      CustomButton()
 }

And I need in the last else to show CustomButton() with some delay. I’ve tried to wrap it in DispatchQueue.main.async but it doesn’t suit there. I mean:

DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
      CustomButton()
 } 

TIA for your opinions and help


Solution

  • You need to change a @State var after the delay. For example:

    struct ContentView: View {
        @State var isButtonHidden = true
        let button = Button("Custom", action: {})
    
        var body: some View {
            Group {
                if isButtonHidden {
                    button.hidden()
                } else {
                    button
                }
            }
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    self.isButtonHidden = false
                }
            }
        }
    }