从这个开始
var body: some View {
ScrollView {
VStack(spacing: 0.0) {
Some views here
}
}
.edgesIgnoringSafeArea(.top)
}
如何添加
List(suggestions, rowContent: { text in
NavigationLink(destination: ResultsPullerView(searchText: text)) {
Text(text)
}
})
.searchable(text: $searchText)
在顶部,如果可滚动的内容?因为无论我如何欺骗这一切当
@State private var suggestions: [String] = []
被填充(非空),搜索结果不会被挤进去(或者更好的是,显示在
的顶部)。"Some views here"
所以我想用不同的术语来实现:搜索字段在顶部,由搜索结果驱动的可滚动内容在下面,下拉搜索建议要么暂时挤压可滚动内容,要么像模态表一样覆盖在顶部。谢谢!
如果你正在寻找像UIKit一样的搜索行为,你必须在覆盖中显示你的结果:
1。让我们声明一个屏幕来显示结果:
struct SearchResultsScreen: View {
@Environment(.isSearching) private var isSearching
var results: [String]?
var body: some View {
if isSearching, let results {
if results.isEmpty {
Text("nothing to see here")
} else {
List(results, id: .self) { fruit in
NavigationLink(destination: Text(fruit)) {
Text(fruit)
}
}
}
}
}
}
2。让我们有一个ObservableObject
来处理逻辑:
class Search: ObservableObject {
static private let fruit = [
"Apples 🍏",
"Cherries 🍒",
"Pears 🍐",
"Oranges 🍊",
"Pineapples 🍍",
"Bananas 🍌"
]
@Published var text: String = ""
var results: [String]? {
if text.isEmpty {
return nil
} else {
return Self.fruit.filter({ $0.contains(text)})
}
}
}
3。最后让我们声明显示搜索栏的主屏幕:
struct ContentView: View {
@StateObject var search = Search()
var body: some View {
NavigationView {
LinearGradient(colors: [.orange, .red], startPoint: .topLeading, endPoint: .bottomTrailing)
.overlay(SearchResultsScreen(results: search.results))
.searchable(text: $search.text)
.navigationTitle("Find that fruit")
}
}
}