【发布时间】:2020-07-05 12:04:50
【问题描述】:
在一个小iOS 应用程序中使用SwiftUI。
有一张地图和一个用于关闭地图的按钮。
我首先阅读了本教程:Advanced MKMapView with SwiftUI 以了解如何在 SwiftUI 中处理 MKMapView,并且它正在工作。这是 MapView 的代码:
(代码几乎完全基于上面提到的教程)
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
@Binding var centerCoordinate: CLLocationCoordinate2D
@Environment(\.presentationMode) var presentationMode
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
appLocalizeMap(mapView)
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
}
// User added code.
func appLocalizeMap(_ mapView: MKMapView) {
let locatSide = 1000.0
mapView.isRotateEnabled = false
mapView.region = MKCoordinateRegion(center: centerCoordinate,
latitudinalMeters: locatSide, longitudinalMeters: locatSide)
}
func dismiss() { // Not currently working ...
self.presentationMode.wrappedValue.dismiss()
}
}
然后我需要设置按钮来关闭地图。这就是我遇到麻烦的地方。
下面是代码,我在其中显示地图并在其顶部设置了一个按钮。 它看起来不错,但只是看起来。没有任何工作。在搜索了网络并阅读了更多内容之后,我感觉我没有将按钮设置在我应该设置的位置。除了我不知道在哪里(大概在 MapView 的代码中)我应该有使地图消失的代码。
ZStack {
MapView(centerCoordinate:
Binding(get: {CLLocationCoordinate2D(
latitude: self.refSpot.userLatitude,
longitude: self.refSpot.userLongitude)},
set: {newValue in}))
.edgesIgnoringSafeArea(.all)
Button(action: {
print("Dismiss Map")
}) {
VStack {
HStack {
Image(uiImage: UIImage(named: "Back.png")!)
.font(.title)
.foregroundColor(.gray)
Spacer()
}
Spacer()
}
}
}
我在其他文档中发现的与取消View 相关的内容似乎不适用于此处的MapView。
任何相关提示将不胜感激。
如果需要,让事情变得更清楚。这是开始时的应用程序:
打开地图按钮按预期工作。当点击它会带来这个:
问题出在最后一张图片左上角的十字形按钮上。此按钮应使地图及其本身消失,返回到第一张图像。
使用此代码(修改):
Button(action: {self.showingMap.toggle()}) {
Text("Open a map")
.font(.largeTitle)
.foregroundColor(.gray)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 30)
.stroke(Color.gray, lineWidth: 4))
}.sheet(isPresented: $showingMap) {
ZStack {
if self.showMap {
MapView(centerCoordinate:
Binding(get: {CLLocationCoordinate2D(
latitude: self.refSpot.userLatitude,
longitude: self.refSpot.userLongitude)},
set: {newValue in}))
.edgesIgnoringSafeArea(.all)
}
Button(action: {
self.showMap.toggle()
}) {
VStack {
HStack {
Image(uiImage: UIImage(named: "Back.png")!)
.font(.title)
.foregroundColor(.gray)
Spacer()
}
Spacer()
}
}
}
}
现在点击十字按钮可以看到这个视图:
虽然地图本身不见了,但十字按钮仍然存在,顶部图像没有回来。
【问题讨论】:
-
我同意 Asperi 的观点。您正在另一个视图中使用 MapView。唯一的选择是根据条件显示它,因为您不能从父视图调用解除函数。 Map View 在这里不是模态/导航链接/工作表视图,所以使用presentationMode没有任何意义。