Reputation: 655
I want to achieve something like this in my SwiftUI project:
I am looking to add a custom button next to the search bar, but I am unable to find relevant information online. Is it possible to achieve this without using custom code, or do I need to use a custom search bar? Thank you in advance for your help.
Upvotes: 0
Views: 1852
Reputation: 36782
You could try this simple all SwiftUI approach, replacing the .searchable(...)
with a .toolbar
containing a TextField
and a Button
in a HStack
.
For example:
struct ContentView: View {
let fruits = ["apples", "pears", "bananas", "apricot", "oranges"]
@State var selection: String?
@State var search = ""
var body: some View {
NavigationStack {
List(selection: $selection) {
ForEach(fruits.filter{searchFor($0)}, id: \.self) { fruit in
Text(fruit).tag(fruit)
}
}
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
HStack {
TextField("🔍 Search", text: $search)
.font(.system(size: 22, weight: .light, design: .default))
.textFieldStyle(.plain)
.background(Color.gray.opacity(0.2))
.clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous))
Button(action: {
print("-----> Button pressed")
// ...
}) {
Image(systemName: "line.3.horizontal.decrease")
}
}
.frame(width: 300, height: 26) // adjust the size to your purpose
}
}
}
}
private func searchFor(_ txt: String) -> Bool {
return (txt.lowercased(with: .current).hasPrefix(search.lowercased(with: .current)) || search.isEmpty)
}
}
Upvotes: 2