完成
NavigationStackの上にSearchBarを置きたい時って結構ありますが、ネット上に良さげなサンプルコードがないんですよね。ということで作りました。

サンプルコード
import SwiftUI
struct ContentView: View {
@State private var searchText = ""
var body: some View {
NavigationStack {
VStack {
SearchBar(text: $searchText)
List() {
Text("あああああ")
Text("いいいいい")
Text("ううううう")
}
}
.navigationBarTitleDisplayMode(.inline)
}
}
}
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
searchBar.autocapitalizationType = .none
searchBar.placeholder = "ここに文字を入力"
searchBar.backgroundImage = UIImage() // SearchBarの上下の線を削除
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBar>) {
uiView.text = text
}
}

