I have this SwiftUI View that was opened via NavigationLink
struct UserSettingsView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
ZStack {
Color("navbar_2280DA").ignoresSafeArea(.all)
Image("profile_background")
.resizable()
.aspectRatio(contentMode: .fill)
.ignoresSafeArea(.all)
}
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
VStack {
Spacer()
HStack {
Button {
presentationMode.wrappedValue.dismiss()
} label: {
Image("btn_arrow_back")
}
Spacer()
}
}
}
}
.toolbar {
ToolbarItem(placement: .principal) {
Text("Settings")
.font(.custom("Poppins-Medium", size: 22))
.kerning(1.76)
}
}
.toolbarBackground(Color("navbar_2280DA"), for: .navigationBar)
.toolbarBackground(.visible, for: .navigationBar)
}
}
The view appears ok, except one thing, toolbar items appear on the navigation bar very high
As you can see, I tried to bring back button down using VStack, and on the screenshot you can barely see the result - back button is tiny bit lower then Navigation Title. I wish to have more control over it, like applying a padding with a contstraint to the bottom of the bar.
I don't want to create custom navigation bar - it is cumbersome and unpleasant experience, I want to use default UI that iOS offers for navigation bars.
Please advise how can I move toolbar items to the bottom of the navigation bar in SwiftUI. Thank you!
I tried your code using SF symbol "chevron.left" and was able to reproduce the issue. But once I removed the VStack
, HStack
and Spacer
around the back button, the arrow was nicely center-aligned with the title. I also tried it with different font sizes and it stayed center-aligned.
So maybe the problem is that your image includes some blank space either at the top or below, which means it is not centered vertically? Or maybe it helps to apply some modifiers to the Image
, like in the code below.
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button {
presentationMode.wrappedValue.dismiss()
} label: {
Image(systemName: "chevron.left") // "btn_arrow_back"
.resizable()
.scaledToFit()
.padding(10)
.frame(width: 44, height: 44)
.foregroundColor(.white)
}
}
}
.toolbar {
ToolbarItem(placement: .principal) {
Text("Settings")
.font(.custom("Poppins-Medium", size: 22))
.kerning(1.76)
}
}
EDIT Following up on your comment: to move the items down, just add top padding:
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button {
presentationMode.wrappedValue.dismiss()
} label: {
Image(systemName: "chevron.left") // "btn_arrow_back"
.resizable()
.scaledToFit()
.padding(10)
.frame(width: 44, height: 44)
.foregroundColor(.white)
.padding(.top, 100) // <- HERE
}
}
}
.toolbar {
ToolbarItem(placement: .principal) {
Text("Settings")
.font(.custom("Poppins-Medium", size: 22))
.kerning(1.76)
.padding(.top, 100) // <- HERE
}
}