I want to add a searchbar to a picker in SwiftUI 2.0. The below demo code implements this, but the searchbar is part of the scrolling list instead of being sticky at the top when the user scrolls through the list. How can I change this?
import SwiftUI
import UIKit
struct ContentView: View {
@State private var selection = 0
@State private var searchText = ""
var body: some View {
NavigationView {
Form {
Picker(selection: $selection, label: Text("Picker")) {
SearchBar(text: $searchText, placeholder: "Search")
ForEach(1 ..< 21) { index in
Text(String(index)).tag(index)
}
}
}
}
}
}
struct SearchBar: UIViewRepresentable {
@Binding var text: String
var placeholder: String
func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.delegate = context.coordinator
searchBar.placeholder = placeholder
searchBar.autocapitalizationType = .none
searchBar.searchBarStyle = .minimal
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBar>) {
uiView.text = text
}
func makeCoordinator() -> SearchBar.Coordinator {
return Coordinator(text: $text)
}
class Coordinator: NSObject, UISearchBarDelegate {
@Binding var text: String
init(text: Binding<String>) {
_text = text
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
}
}
}