【问题标题】:How would I make my map annotation open the correct view? - Swift如何让我的地图注释打开正确的视图? - 斯威夫特
【发布时间】:2021-06-15 10:19:45
【问题描述】:

我正在尝试这样做,以便每次单击地图注释时都会出现相应的视图,但似乎并非如此。看起来它混合在一起,有时会多次出现相同的视图。这是我到目前为止的代码:

 Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true, userTrackingMode: nil, annotationItems: sclocations) { item in
                    MapAnnotation(coordinate: item.location) {
                        Button(action: {
                            self.activeSheet = .sheetA
                        }, label: {
                            Image(systemName: "mappin")
                                .foregroundColor(.red)
                        }) //: BUTTON
                        .sheet(item: $activeSheet) { sheet in
                            switch sheet {
                                case .sheetA:
                            SCDetailView(sclocations: item)
                            }
                        }
                    }
                }

【问题讨论】:

  • 对于“同一视图显示多次”问题,您可能需要使用sheet(item:) 而不是sheet(isPresented:)。见stackoverflow.com/a/66162319/560942
  • 好吧,它们都包含在同一个视图中,但视图中的信息应该不同(由于视图链接到的 JSON 文件)取决于选择的 pin,所以我不认为将工作。 @jnpdx
  • 我明白这一点。我建议由于 iOS 14 的功能,您可能希望使用 sheet(item:) 表单而不是 sheet(presented:) 以便为工作表显示正确的数据。
  • 我更新了我的代码。它仍然不起作用,每当我单击任何引脚时,它都会随机化视图。 @jnpdx
  • 您必须为项目实际分配一些东西:该参数对于识别要描述的工作表很有用。我可以稍后再写一个答案。

标签: swift swiftui mapkit mapkitannotation


【解决方案1】:

我将不得不在这里做一些假设,因为您没有显示item 的类型。假设它被称为LocationItem。重要的是它符合Identifiable

struct LocationItem : Identifiable {
    var id = UUID()
    var name : String
    var location: CLLocationCoordinate2D
}

您需要一个 @State 变量来在您的视图上存储一个可选的 LocationItem

@State var locationItem : LocationItem?

您的按钮将设置locationItem

Button(action: {
   self.locationItem = item
})

您的sheet 电话将如下所示:

.sheet(item: $locationItem) { locationItem in
   SCDetailView(sclocations: locationItem) //note how I'm using locationItem here -- the parameter from the closure                          
}

最后,我将移动 sheet 使其在您的 MapAnnotation 之外,这样您的整个视图主体看起来更像:

Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true, userTrackingMode: nil, annotationItems: sclocations) { item in
                    MapAnnotation(coordinate: item.location) {
                        Button(action: {
                            self.locationItem = item
                        }) {
                           Image(systemName: "mappin").foregroundColor(.red)
                        }
                    }
                }
.sheet(item: $locationItem) { locationItem in
   SCDetailView(sclocations: locationItem)                    
}

请记住,由于您没有提供完整的代码示例,就像我说的那样,我猜测了一些事情,因此您可能必须将其推断到您自己的解决方案中(例如将您的类型设置为 Identifiable )。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多