Is it possible to make the navbar title clickable like a button?
Tried .navigationBarTitle(Button(....)), but this won’t work bc button doesn't conform to string protocol...
3 Answers
struct ContentView: View {
var body: some View {
NavigationView {
GeometryReader { geo in
List {
Text("Have a nice day!")
Text("Today is sunny")
}.navigationBarTitle(Text(""), displayMode: .inline)
.navigationBarItems(leading: HStack{
Spacer().frame(width: geo.size.width * 0.5)
VStack{
Text("Title")
Button(action: {
print("I'm feeling lucky ;)")
})
{
Text("Button")
}
}
Spacer().frame(width: geo.size.width * 0.5)
})
}
}
}
}
1 Comment
Alex Ioja-Yang
If only this also allowed to still have a leading button...
As mentioned in this answer, from iOS 14 onwards, the toolbar view modifier can be used to place a ToolBarItem in the navigation bar. A ToolBarItem can be any view that conforms to the ToolbarContent protocol.
Note: If you want to make the toolbar content appear in place of the navigation title, make sure to set the placement parameter as .principal. Here is an example:
.toolbar {
ToolbarItem(placement: .principal) {
Button {
// Your button action here
} label: {
// your button label here
Text("I am a button")
}
}
}
3 Comments
Claudiu
is it possible to make the button appear in place of the title also for the case where the title is in large display mode?
NSSpeedForce
@Claudiu I’m not sure but you can try out the different options for placement. Replace .principal with other options and see if there is a way to accomplish that
Claudiu
I tried it, it is not working unfortunately

