Thursday, December 1, 2022
HomeiOS Developmentios - SwiftUI - Hiding navigation bar during certain conditions

ios – SwiftUI – Hiding navigation bar during certain conditions

[ad_1]

Is it possible to show/hide navigation bar on the view while the view is open, but during certain conditions I wish to show navigation bar and during other conditions I wish to hide it.

Let’s say when I open the view, I wish to show navigation bar with title, but when an event gets canceled, I display a message on the view and during this point I wish to hide the nav bar. For this I am creating a state var “showNavBar” which I initially set to false and then when an event is canceled i.e. view model’s state changes to ‘eventCanceled’, in my view I am updating state variable’s value to true. However, when
“showNavBar” is set to true, I don’t see navigation bar hiding from the view.

Is it possible to show and hide navigation bar when the view is open?

Below is the code:

class CustomViewModel: ObservableObject {
    enum EventDetailsStates {
        case idle
        case loading
        case eventCanceled
    }
    @Published var state = EventDetailsStates.idle
    @Published var reloadData = false
    
    init() {
        NotificationCenter.default.addObserver(forName: Notification.Name("eventCanceled"), object: nil, queue: nil, using: self.processEventCanceledNotification(_:))
    }
    
    @objc func processEventCanceledNotification(_ notification: Notification) {
        // Do something
        self.reloadData = false
        self.state = .eventCanceled
     }
}

struct CustomView: View {
    @ObservedObject var viewModel: CustomViewModel
    @State var showMessageView = false
    @State var showNavBar = false
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        VStack {
            switch viewModel.state {
            // Some other states.

            case .eventCanceled:
            if self.showMessageView {
                MessageView().onAppear() {
                    self.showNavBar = false
                }.onDisappear() {
                    presentationMode.wrappedValue.dismiss()
                }
            }
            }
        }.navigationBarBackButtonHidden(showNavBar).navigationBarHidden(showNavBar).navigationBarTitle("Back")
        .onAppear() {
            if viewModel.reloadData {
                viewModel.state = .idle
            } else {
                self.showMessageView = true
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 15.0) {
                    self.showMessageView = false
                }
            }
        }
    }
}

[ad_2]

Source link

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments