我正在努力做到这一点,以便根据单击的地图注释显示不同的视图。我正在使用 navigationView 并且无法使目的地成为有条件的。
import MapKit
import SwiftUI
struct Location: Identifiable {
let id = UUID()
let name: String
let coordinate: CLLocationCoordinate2D
let symbol: String
}
struct ContentView: View {
@State private var mapRegion = MKCoordinateRegion (center: CLLocationCoordinate2D(latitude: 51.5, longitude: -0.12), span: MKCoordinateSpan (latitudeDelta: 0.2, longitudeDelta: 0.2))
let locations = [ Location (name: "Buckingham Palace", coordinate: CLLocationCoordinate2D(latitude:
51.508, longitude: -0.076),symbol: "house"), Location(name: "Tower of London", coordinate: CLLocationCoordinate2D(latitude: 57.919, longitude: 12.577), symbol: "key")
]
var body: some View {
NavigationView {
Map(coordinateRegion: $mapRegion, annotationItems: locations) { location in MapAnnotation(coordinate: location.coordinate) {
NavigationLink ( destination: if location.symbol == "house"{ View2()} else {View3()}
}) {
ZStack{
Circle()
.frame(width: 35, height: 35)
.foregroundColor(.orange)
Image(systemName: location.symbol)
.foregroundColor(.white)
}
}
}
.onAppear {
MKMapView.appearance().mapType = .satellite
}
.ignoresSafeArea()
}
.navigationViewStyle(.stack)
}
}
struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView()
}
}
我试过在 navigationlink() 中使用 if 语句,但它不起作用。
您可以尝试这种不同的方法,使用
NavigationStack
,而不是弃用的 NavigationView,Button
和 switch
在navigationDestination
。对我来说效果很好。
struct Location: Identifiable {
let id = UUID()
let name: String
let coordinate: CLLocationCoordinate2D
let symbol: String
}
struct ContentView: View {
@State private var mapRegion = MKCoordinateRegion (center: CLLocationCoordinate2D(latitude: 51.5, longitude: -0.12), span: MKCoordinateSpan (latitudeDelta: 0.2, longitudeDelta: 0.2))
let locations = [
Location(name: "Buckingham Palace", coordinate: CLLocationCoordinate2D(latitude: 51.501, longitude: -0.141), symbol: "house"),
Location(name: "Tower of London", coordinate: CLLocationCoordinate2D(latitude: 51.508, longitude: -0.076), symbol: "key")
]
@State private var path = NavigationPath() // <-- here
var body: some View {
NavigationStack(path: $path) { // <-- here
Map(coordinateRegion: $mapRegion, annotationItems: locations) { location in MapAnnotation(coordinate: location.coordinate) {
Button(action: { path.append(location.symbol) }) { // <-- here
ZStack {
Circle().frame(width: 55, height: 55).foregroundColor(.orange)
Image(systemName: location.symbol).foregroundColor(.white)
}
}
}
}.onAppear {
MKMapView.appearance().mapType = .satellite
}
.ignoresSafeArea()
.navigationDestination(for: String.self) { val in // <-- here
switch val {
case "house": View2()
case "key": View3()
default: View1()
}
}
}
.navigationViewStyle(.stack)
}
}
struct View1: View {
var body: some View {
Text("View1")
}
}
struct View2: View {
var body: some View {
Text("View2")
}
}
struct View3: View {
var body: some View {
Text("View3")
}
}