【发布时间】:2021-09-25 17:18:02
【问题描述】:
每次更改 ContentView 中的“位置”变量时,我的 MapView“注释”变量如何更新?我用谷歌搜索了 swift 数组是一种值类型,我什至不需要在“注释”上使用绑定并绑定到“位置”,以便“注释”了解“位置”何时发生变化,这是为什么呢?
import SwiftUI
import MapKit
struct ContentView: View {
@State var centerCoordinate = CLLocationCoordinate2D()
@State var locations = [MKPointAnnotation]()
var body: some View {
ZStack{
MapView(centerCoordinate: $centerCoordinate, annotations: locations)
Circle()
.fill(Color.blue)
.opacity(0.5)
.frame(width: 32, height: 32, alignment: .center)
VStack{
Spacer()
HStack{
Spacer()
Button(action: {
let newLocation = MKPointAnnotation()
newLocation.coordinate = centerCoordinate
locations.append(newLocation)
}){
Image(systemName: "plus")
}
.padding()
.background(Color.black.opacity(0.75))
.foregroundColor(.white)
.font(.title)
.clipShape(Circle())
.padding([.trailing, .bottom])
}
}
}
.edgesIgnoringSafeArea(.all)
}
}
struct MapView: UIViewRepresentable{
@Binding var centerCoordinate: CLLocationCoordinate2D
var annotations: [MKPointAnnotation]
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
return mapView
}
// Callback function - when anything being sent to UIViewRepresentabel struct is changed
func updateUIView(_ uiView: UIViewType, context: Context) {
print("Updating UIView")
if annotations.count != uiView.annotations.count{
uiView.removeAnnotations(uiView.annotations)
uiView.addAnnotations(annotations)
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate {
let parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
parent.centerCoordinate = mapView.centerCoordinate
}
}
}
extension MKPointAnnotation{
static var example: MKPointAnnotation{
let point = MKPointAnnotation()
point.coordinate = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.13)
point.title = "London"
point.subtitle = "The home of 2012 Summer Olympics"
return point
}
}
【问题讨论】: