在使用 MKRoutes 制作折线的 SwiftUI iOS 17 应用程序的 MapKit 中,我想在绘制路线时将 ProgressView 放置在地图顶部(并在完成之前禁用任何其他用户交互)。看来 MapPolyline() 函数需要位于 Map 闭包中,并且不能在外部进行重构,但我尝试将其包装在任务或 if 语句中的任何操作都失败了。
这是演示的简化版本:
struct ContentView: View {
@State private var routes = [MKRoute]()
@State private var showProgress: Bool = false
var body: some View {
ZStack {
Map() {
//want to start a ProgressView here
if routes.count >= 1 {
ForEach(routes, id: \.self) { r in
MapPolyline(r)
.stroke(.blue, lineWidth: 4)
}
}// if routes
//want to end a ProgressView here
}
.onAppear {
makeSomeRoutes()
}
if showProgress {
ProgressView()
.tint(.red)
.scaleEffect(4)
}
}//z
}//body
func makeSomeRoutes() {
let lats: [CLLocationDegrees] = [
37.338207,
38.5816,
39.1677,
40.760780
]
let longs: [CLLocationDegrees] = [
-121.886330,
-121.4944,
-120.1452,
-111.891045
]
for r in 0..<3 {
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lats[r], longitude: longs[r])))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lats[r + 1], longitude: longs[r + 1])))
Task {
let result = try? await MKDirections(request: request).calculate()
let aRoute = result?.routes.first
if let aRoute {
self.routes.append(aRoute)
}
}
}//for
}//make some routes
}//struct
任何指导将不胜感激。 Xcode 15、iOS 17
您可以尝试使用
Annotation
来握住 ProgressView
。
// for testing, adjust accordingly
let center = CLLocationCoordinate2D(latitude: 39.1677, longitude: -120.1452)
var body: some View {
ZStack {
Map() {
if routes.count >= 1 {
ForEach(routes, id: \.self) { r in
MapPolyline(r).stroke(.blue, lineWidth: 8)
}
} else {
Annotation("", coordinate: center) {
ProgressView().tint(.red).scaleEffect(4)
}
}
}
}
.onAppear {
makeSomeRoutes()
}
}//body