Navigation Bar hide is not working in SwiftUI
I tried multiple solutions, including UINavigationControllerDelegate and nothing seems to make the navigationBar permanently hidden. Until I tried KVO :)
So if you want a permanent solution, use this:
struct NoBarNavigationView<Content: View>: View {
private let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
NavigationView {
content
.introspectNavigationController { (UINavigationController) in
NavigationControllerDelegate.shared.becomeDelegate(of: UINavigationController)
}
}
}
}
class NavigationControllerDelegate: NSObject {
static let shared = NavigationControllerDelegate()
func becomeDelegate(of navigationController: UINavigationController) {
navigationController.isNavigationBarHidden = true
navigationController.navigationBar.isHidden = true
navigationController.navigationBar.addObserver(self, forKeyPath: "alpha", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// This is necessary to ensure the UINavigationBar remains hidden
if let navigationBar = object as? UINavigationBar {
navigationBar.isHidden = true
}
}
}
Happy coding!
EDIT: As pointed out in the comments, I am using:
import Introspect
GitHub link
NOTE: (For some reason it works in some cases) SwiftUI
requires that you need to .navigationBarTitle
for .navigationBarHidden
to work properly.
NavigationView {
ScrollView() {
......
}.
.navigationBarTitle("") //this must be empty
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}