问题
I installed the Mapbox SDK into my project, but I don't understand how to integrate this code snippet with SwiftUI
.
I created a SwiftUI View
named MapView
, where I import the Mapbox Framework.
I try to use the UIViewRepresentable
protocol, as in Apple's tutorial, but without success.
import Mapbox
class MapView: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let styleURL = URL(string: "mapbox://styles/mapbox/outdoors-v9")
let mapView = MGLMapView(frame: view.bounds,
styleURL: styleURL)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.setCenter(CLLocationCoordinate2D(latitude: 45.52954,
longitude: -122.72317),
zoomLevel: 14,
animated: false)
view.addSubview(mapView)
}
}
I am new to iOS development, so any help would be much appreciated.
回答1:
This is a working sample on how you can integrate the MGLMapView
with SwiftUI
.
When using UIViewRepresentable
you have to implement two delegates: makeUIView
that will return your view (in this case MGLMapView
) and updateUIView
which will receive the same view type as the one returned in makeUIView
(again MGLMapView
).
You can use this to experiment.
Also I recommend you get familiar with the React architecture to understand better the SwiftUI approach.
You can improve this sample by making ContentView
receive a styleURL, and trying different styles in the preview.
import Mapbox
import SwiftUI
struct ContentView : View {
var body: some View {
MapboxViewRepresentation(MGLStyle.streetsStyleURL)
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
struct MapboxViewRepresentation : UIViewRepresentable {
let styleURL: URL
init(_ styleURL: URL) {
self.styleURL = styleURL
}
func makeUIView(context: UIViewRepresentableContext<MapboxViewRepresentation>) -> MGLMapView {
let mapView = MGLMapView(frame: .zero, styleURL: styleURL)
return mapView
}
func updateUIView(_ uiView: MGLMapView, context: UIViewRepresentableContext<MapboxViewRepresentation>) {
}
}
UPDATE: Here is the official guide on how to integrate Mapbox with SwiftUI https://docs.mapbox.com/help/tutorials/ios-swiftui/
来源:https://stackoverflow.com/questions/56551145/how-to-integrate-mapbox-sdk-with-swiftui