I am trying to add a second line of buttons in my toolbar navigation view in SwiftUI so that it looks like this: However, these bottom buttons lose their functionality. I put them in a HStack in the Toolbar.
This HStack
is located in a VStack
in a ToolbarItemGroup
object. Does anyone know why these buttons do not notice when they are clicked?
The ForEach
does not seem to be the problem because the button still does not work when it is just one of them. However, when it is placed outside of the HStack
, it does work.
See code below:
ContentView
:
struct ContentView: View {
@State var searchQuery: String = ""
@State var showNavigationBar = true
@State var tabView: String = "home"
@FocusState var searchInFocus: Bool
var body: some View {
NavigationStack {
TabView(selection: $tabView) {
Text("Hello World!")
}.toolbar(showNavigationBar ? .visible : .hidden)
.toolbar {
searchNav
}
}.navigationDestination(for: Int.self) { newView in
// destination view
}
}
}
ToolbarItemGroup
:
extension ContentView {
@ToolbarContentBuilder var searchNav: some ToolbarContent {
ToolbarItemGroup(placement: .navigation) {
VStack {
HStack {
TextField("", text: $searchQuery, prompt: Text("Search Cleo.").foregroundColor(.black))
.focused($searchInFocus)
.imageScale(.large)
.padding(.top, 20)
Button {
searchQuery = ""
tabView = "home"
} label: {
Image(systemName: "line.3.horizontal")
.foregroundColor(Color(.black))
.imageScale(.large)
.frame(width: 50)
.frame(height: 40)
.background(Color(#colorLiteral(red: 0.7750167251, green: 0.8043509126, blue: 0.8005430698, alpha: 0.7539859694)))
.cornerRadius(25)
}.padding(.top, 20)
}
HStack(spacing: 0) {
ForEach(0..<4) {buttonType in
Button {
print("clicked \(String(buttonType))")
// THIS IS THE PART THAT DOESN'T WORK
} label: {
Text(String(buttonType))
}
}
}.padding(.vertical)
}
}
}
}
Note that this code does not look nice on when rendered, yet it still highlights the main issue of the buttons not responding to clicks.