我有一个符合UIViewControllerRepresentable的SearchController,并且已经实现了必需的协议方法。但是,当我在SwiftUI结构中创建SearchController的实例时,一旦加载,SearchController不会出现在屏幕上。有人对我如何将UISearchController与SwiftUI集成有任何建议吗?谢谢!
这是符合UIViewControllerRepresentable的SearchController结构:
struct SearchController: UIViewControllerRepresentable {
let placeholder: String
@Binding var text: String
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIViewController(context: Context) -> UISearchController {
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = context.coordinator
controller.obscuresBackgroundDuringPresentation = false
controller.hidesNavigationBarDuringPresentation = false
controller.searchBar.delegate = context.coordinator
controller.searchBar.placeholder = placeholder
return controller
}
func updateUIViewController(_ uiViewController: UISearchController, context: Context) {
uiViewController.searchBar.text = text
}
class Coordinator: NSObject, UISearchResultsUpdating, UISearchBarDelegate {
var controller: SearchController
init(_ controller: SearchController) {
self.controller = controller
}
func updateSearchResults(for searchController: UISearchController) {
let searchBar = searchController.searchBar
controller.text = searchBar.text!
}
}
}
这是我的SwiftUIView的代码,应显示SearchController:
struct SearchCarsView: View {
let cars = cardsData
// MARK: @State Properties
@State private var searchCarsText: String = ""
// MARK: Views
var body: some View {
SearchController(placeholder: "Name, Model, Year", text: $searchCarsText)
.background(Color.blue)
}
}
这是SearchController的图像未出现在屏幕上:
在这种情况下,实际视觉元素是UISearchBar
,因此最简单的起点应如下
import SwiftUI
import UIKit
struct SearchView: UIViewRepresentable {
let controller = UISearchController()
func makeUIView(context: UIViewRepresentableContext<SearchView>) -> UISearchBar {
self.controller.searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchView>) {
}
typealias UIViewType = UISearchBar
}
struct TestSearchController: View {
var body: some View {
SearchView()
}
}
struct TestSearchController_Previews: PreviewProvider {
static var previews: some View {
TestSearchController()
}
}
接下来的所有操作都可以像往常一样在init中进行配置,并作为委托进行协调。
我曾尝试使UISearchController与NavigationView和UIViewRepresentable配合使用以注入搜索控制器,但结果确实有问题。可能最好的方法是使用常规的UINavigationController而不是NavigationView,然后再使用容器UIViewController,在其中将NavigationItem.searchController设置为UISearchController。