I have an app, which displays logo in the center of the NavigationBar in SwiftUI. The app is using NavigationStack in iOS 16. Here is the implementation.
struct DetailView: View {
var body: some View {
Text("Detail View")
}
}
struct ContentView: View {
var body: some View {
NavigationStack {
VStack {
NavigationLink("Detail", value: "Detail")
.toolbar {
ToolbarItem(placement: .principal) {
Image(systemName: "heart.fill")
.foregroundColor(.red)
}
}
}.navigationDestination(for: String.self) { stringValue in
DetailView()
}
}
}
}
This displays the heart logo in the center of the NavigationBar but as soon as I go to DetailView, the heart logo is gone. How can I make sure that the heart logo is available on app the navigation bars in the app.
UPDATE: I can solve this problem by creating a custom NavigationContainerView as shown below:
struct CustomNavigationView<Header: View, Content: View>: View {
let header: Header
let content: () -> Content
init(header: Header, content: @escaping () -> Content) {
self.header = header
self.content = content
}
var body: some View {
VStack {
Image(systemName: "heart.fill")
.foregroundColor(.red)
NavigationStack {
content()
.navigationDestination(for: String.self) { stringValue in
Text("Detail")
}
}
.toolbar {
ToolbarItem(placement: .principal) {
header
}
}
}
}
}
But this creates a small gap between the NavigationBar and the back button as shown below:
UPDATE: ZStack approach does not show the image at all.
struct CustomNavigationView<Content: View>: View {
let content: () -> Content
init(content: @escaping () -> Content) {
self.content = content
}
var body: some View {
ZStack(alignment: .top) {
Image(systemName: "heart.fill")
.foregroundColor(.red)
NavigationStack {
content()
.navigationDestination(for: String.self) { stringValue in
Text("Detail")
}
}
}
}
}
struct CustomNavigationView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
CustomNavigationView {
Text("DETAIL")
}
}
}
}
CodePudding user response:
A possible approach is to use instead ZStack
with top alignment, like
var body: some View {
ZStack(alignment: .top) { // << here !!
Image(systemName: "heart.fill")
.foregroundColor(.red).zIndex(1)
NavigationStack {
content()
.navigationDestination(for: String.self) { stringValue in
Text("Detail")
}
}