如何解决循环值显示相同的点击结果
我已经为 countries
导入了 JSON:
Countries.json(示例)
[
{
display_name: "France",timezone: "placeholder",longitude: 13.33,latitude: 15.34
},{
display_name: "California",timezone: "EST",longitude: 33.33,latitude: 12.34
},]
我有一个函数 getAnnotated
,它遍历国家/地区以生成 AnnotatedItem
数组。这在 Map
中使用并作为 item
循环以实际创建 MapAnnotation
。然后将 item
传递给辅助函数 getCountry
。我过滤 countries
以获取与 display_name
具有相同 item
字段的国家/地区。
所需的行为是在每个国家/地区都有一个注释/标记,点击该注释将弹出一个模式/表格,提供有关该国家/地区的信息。
我的问题是,如果我放大并且屏幕上只有一个注释/标记,则单击它时会显示正确的国家/地区。
如果我缩小地图并且有多个注释,我点击的每个注释都会为每个注释弹出相同的 country
信息。我认为我的循环方式有问题。
var countries = Bundle.main.decode("Countries.json")
struct AnnotatedItem: Identifiable {
let id = UUID()
var name: String
var coordinate: CLLocationCoordinate2D
}
struct MapView: View {
@State var showSheet = false
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: 25.7617,longitude: 80.1918
),span: MKCoordinateSpan(
latitudeDelta: 10,longitudeDelta: 10
)
)
func getAnnotated() -> [AnnotatedItem] {
var pointsOfInterest = [AnnotatedItem]()
for i in countries {
pointsOfInterest.append(AnnotatedItem(name: i.display_name,coordinate: .init(latitude: i.latitude,longitude: i.longitude)))
}
return pointsOfInterest
}
func getCountry(newItem: AnnotatedItem) -> Country {
let country = countries.filter{ $0.display_name == newItem.name }
return country[0]
}
var body: some View {
Map(coordinateRegion: $region,annotationItems: getAnnotated()) { item in
MapAnnotation(coordinate: item.coordinate) {
Button(action: {
showSheet.toggle()
}){
Image(systemName: "airplane")
.foregroundColor(.white)
.padding()
}
.background(Circle())
.foregroundColor(Color.green)
.sheet(isPresented: $showSheet) {
SheetView(country: getCountry(newItem: item))
}
}
}
}
}
解决方法
我会尝试这样的事情来实现所需的行为:
class SelectedCountry: ObservableObject {
@Published var item: AnnotatedItem = AnnotatedItem(name: "no name",coordinate: CLLocationCoordinate2D())
}
struct MapView: View {
@ObservedObject var selected = SelectedCountry() // <--- here
@State var showSheet = false
...
var body: some View {
Map(coordinateRegion: $region,annotationItems: getAnnotated()) { item in
MapAnnotation(coordinate: item.coordinate) {
Button(action: {
selected.item = item // <--- here
showSheet.toggle()
}){
Image(systemName: "airplane")
.foregroundColor(.white)
.padding()
}
.background(Circle())
.foregroundColor(Color.green)
}
}
// ---> put the sheet here
.sheet(isPresented: $showSheet) {
SheetView(country: getCountry(newItem: selected.item))
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。