In iOS SwiftUI, how can we make a common layout for the navigation bar, so we can use that in all projects without rewriting the same code?
We can use ViewBuilder to create a base view for common code as follows:
struct BaseView<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
// To-do: The most important part will go here
}
}
How can we add navigation bar code in View Builder or base view?
2
Answers
One way to achieve this is to use a custom view as an overlay.
For example, consider the below code which makes a custom navigation bar using an overlay:
The ZStack inside the
.overlay
will make a view that looks like a navigation bar. You can then move it to its own struct view, add different variables to it and call it from the overlay.You can create an extension of
view
like this way. You can check out my blog entry for details.Now you can use this appBar in any place of the view.