SwiftUI official tutorial (V)
The use UIKit and SwiftUI
At this point, we are ready to create a map view, then use MapKit
the MKMapView
class to render a map.
In SwiftUI
use, UIView
a subclass, you need to follow in other view packaging UIViewRepresentable
protocol SwiftUI
view in. SwiftUI
And it includes WatchKit
, AppKit
View similar agreements.
First, we can create a presentation MKMapView
to customize the view.
SwiftUI Tutorial
5.1 Select File
> New
> File
, select iOS
the platform, select the SwiftUI View
template, and then click Next
. The new file name MapView.swift
, and then click Create
.
5.2 to MapKit
add a import
statement to declare MapView
type follows UIViewRepresentable
.
Xcode can ignore the error, the next steps will be to solve these problems.
SwiftUI Tutorial
MapView.swift
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
var body: some View {
Text("Hello World")
}
}
struct MapView_Preview: PreviewProvider {
static var previews: some View {
MapView()
}
}
UIViewRepresentable
Protocol need to implement two methods: makeUIView(context:)
to create a MKMapView
, updateUIView(_:context:)
to view and respond to configuration changes.
5.3 with makeUIView(context:)
alternative method body
attribute, the method creates and returns a null MKMapView
.
MapView.swift
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
typealias UIViewType = MKMapView
func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
return MKMapView(frame: .zero)
}
}
struct MapView_Preview: PreviewProvider {
static var previews: some View {
MapView()
}
}
5.4 to achieve updateUIView(_:context:)
a method, to set the coordinate map view, so that in Turtle Rock
the center.
MapView.swift
import SwiftUI
import MapKit
struct MapView : UIViewRepresentable {
typealias UIViewType = MKMapView
func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
return MKMapView(frame: .zero)
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MapView>) {
let coordinate = CLLocationCoordinate2D(
latitude: 34.011286, longitude: -116.166868)
let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
let region = MKCoordinateRegion(center: coordinate, span: span)
uiView.setRegion(region, animated: true)
}
}
struct MapView_Preview: PreviewProvider {
static var previews: some View {
MapView()
}
}
When the preview in static mode
the display only SwiftUI
view. Because MKMapView
a UIView
subclass, you need to switch to the real-time mode to see the map.
SwiftUI Tutorial
5.5 click Live Preview
can switch to Live Preview mode, sometimes used Try Again
or Resume
buttons.
After a few moments, you will see Joshua Tree National Park
the map, which is the Turtle Rock
hometown.