For reusability, I create the search bar as a seperate view, but you can also implement it right into your view.
struct SearchBar: View {
var placeholder: String
@Binding var text: String
var body: some View {
TextField(placeholder, text: $text)
}
}
Now you have a simple TextField, but it doesn’t have any styling yet.
SearchBar(placeholder: “Search …”, text: $text)
The next thing we will add is a clear button, that sets the text
back to ""
.
HStack {
TextField(placeholder, text: $text)
if text != "" {
Image(systemName: "xmark.circle.fill")
.imageScale(.medium)
.foregroundColor(Color(.systemGray3))
.padding(3)
.onTapGesture {
withAnimation {
self.text = ""
}
}
}
}
#ios #swift #xcode #swiftui