我想在我的 SwiftUI 项目中实现这样的目标:
我希望在搜索栏旁边添加一个自定义按钮,但我无法在线找到相关信息。是否可以在不使用自定义代码的情况下实现此目的,或者我是否需要使用自定义搜索栏?预先感谢您的帮助。
您可以尝试这个简单的全 SwiftUI 方法,替换
.searchable(...)
其中 .toolbar
包含 TextField
和 Button
中的 HStack
。
例如:
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)
}
}