我正在尝试使用 SwiftUI 重新创建每个人都知道的 UITableView:tableview 标题中的一个简单搜索字段:
但是,SwiftUI 中的 ListView 似乎甚至没有添加页眉或页脚的方法。您可以将带有 TextField 的标题设置为这样的部分:
@State private var searchQuery: String = ""
var body: some View {
List {
Section(header:
Group{
TextField($searchQuery, placeholder: Text("Search"))
.background(Color.white)
}) {
ListCell()
ListCell()
ListCell()
}
}
}
但是,我不确定这是否是最好的方法,因为:
有没有人找到好的方法?我不想依赖 UITableView。
最佳答案
Xcode 13/SwiftUI 3
您现在可以使用 .searchable
制作一个列表......可搜索!
struct ContentView: View {
@State private var searchQuery: String = ""
var body: some View {
NavigationView {
List {
ForEach(Array(1...100)
.map { "\($0)" }
.filter { searchQuery.isEmpty ? true : $0.contains(searchQuery) }
,id: \.self) { item in
Text(verbatim: item)
}
}
.navigationTitle("Fancy Numbers")
.searchable(text: $searchQuery)
}
}
}
搜索栏似乎只有在 List
时才会出现嵌入在 NavigationView
中.Xcode 12,SwiftUI 1/2
您可以端口
UISearchBar
到 SwiftUI。(有关这方面的更多信息可以在 WWDC 2019 的精彩演讲中找到 - Integrating SwiftUI)
struct SearchBar: UIViewRepresentable {
@Binding var text: String
class Coordinator: NSObject, UISearchBarDelegate {
@Binding var text: String
init(text: Binding<String>) {
_text = text
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text)
}
func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.delegate = context.coordinator
return searchBar
}
func updateUIView(_ uiView: UISearchBar,
context: UIViewRepresentableContext<SearchBar>) {
uiView.text = text
}
}
并像这样使用它:struct ContentView: View {
@State private var searchQuery: String = ""
var body: some View {
List {
Section(header: SearchBar(text: self.$searchQuery)) {
ForEach(Array(1...100).filter {
self.searchQuery.isEmpty ?
true :
"\($0)".contains(self.searchQuery)
}, id: \.self) { item in
Text("\(item)")
}
}
}
}
}
这是正确的搜索栏,但它不会隐藏 - 我相信我们可以在某个时候通过 SwiftUI API 做到这一点。看起来像这样 :
关于uitableview - SwiftUI - 在列表标题中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56608996/