I am trying to make the search box in .searchable stick to the top without moving when there is no navigationBarTitle. Basically, when the box gets focused, there is an animation that moves the box upward and I would like to prevent that from hapenning. I just want the searchbox to stay stationary at the top, with just the cancel button coming from the right when the box is focused.
I tried all type of things such as .navigationBarHidden(true) but this totally removes the search bar as a whole.
Tried to add some spacer under in a vstack but it didnt push the bar up when unfocused, i tried to add some .ignoreSafeArea() but it didnt work. I tried to add a geometryReader and make the screen height larger than the display but it didnt move things up.
My codes:
struct SearchBarSM: View {
@State var searchtxt:String = ""
var body: some View {
GeometryReader { geo in
NavigationStack {
ZStack {
VStack {
Text("Hello stackoverflow")
}
}
.navigationBarTitle("")
.searchable(text: $searchtxt, prompt: "Search") {
}
.preferredColorScheme(.dark)
}
}
}
}
The box moves up when focused.
2
Answers
As devdchaudhary said in the comments, I doubt this can be changed. You need to make your own search bar, and put it in the
.principal
position of the toolbar.It’s not that difficult to make your own search bar. Here, I have made something that behaves similar to the system’s search bar. Adjust the colors and paddings as you see fit.
Usage:
To achieve the behavior you described, you have to make a search bar view custom and then put it into the SearchBarSM view.
Example code:
SearchableCustom: View
SearchBarSM: View