最近我尝试将 Mapbox 默认搜索 UI 集成到我的项目中。我的项目基本上是基于 SwiftUI 的,Mapbox 网站上的使用示例是使用 UIKit。我试图将 UIKit 包装到 SwiftUI 代码中。这是我在符合协议'UIViewControllerRepresentable'的SearchController上写的:
struct Search: UIViewControllerRepresentable, LocationProvider {
let userCoordinate = CLLocationCoordinate2D(latitude: 37.785834, longitude: -122.406417)
/// `LocationProvider` protocol implementation
func currentLocation() -> CLLocationCoordinate2D? { userCoordinate }
func makeUIViewController(context: UIViewControllerRepresentableContext<Search>) -> MapboxPanelController {
let searchController = MapboxSearchController(locationProvider: self)
// default panel
let panelController = MapboxPanelController(rootViewController: searchController)
searchController.delegate = context.coordinator
return panelController
}
func updateUIViewController(_ uiViewController: MapboxPanelController, context: UIViewControllerRepresentableContext<Search>) {
}
...
}
而我写的父内容视图:
...
var body: some View {
VStack{
ZStack {
NavigationMap()
Search(annotations: $annotations, position: $position)
}
}
}
...
NavigationMap() 是我在另一个文件上创建的 MapView。基本上我在这里尝试做的是通过 Mapbox 添加一个默认的 panelController 作为 NavigationMap 的子视图。但是我运行的结果是我无法再与 NavigationMap 交互。似乎 searchController 完全覆盖了 NavigationMap,即使使用 panelController 允许您上下拖动面板。我不知道我做错了什么。以下是 Mapbox 提供的原始文档:
class SimpleUISearchViewController: UIViewController, LocationProvider {
lazy var searchController = MapboxSearchController(locationProvider: self)
/// `LocationProvider` protocol implementation
func currentLocation() -> CLLocationCoordinate2D? { mapboxSFOfficeCoordinate }
lazy var panelController = MapboxPanelController(rootViewController: searchController)
let mapView = MGLMapView()
let mapboxSFOfficeCoordinate = CLLocationCoordinate2D(latitude: 37.7911551, longitude: -122.3966103)
override func viewDidLoad() {
super.viewDidLoad()
/// Add MGLMapView on the screen
mapView.frame = view.bounds
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.showsUserLocation = true
mapView.setCenter(mapboxSFOfficeCoordinate, zoomLevel: 15, animated: false)
view.addSubview(mapView)
searchController.delegate = self
addChild(panelController)
}
...
}
我不确定为什么我在 SwiftUI 中实现了错误的方式,或者它提供的默认文档不能完全支持 SwiftUI。有人可以帮我吗?我很感激。