【问题标题】:Problem with callout button and firestore in swiftswift中的标注按钮和firestore出现问题
【发布时间】:2021-03-28 13:54:25
【问题描述】:

我在 Firestore 上有 5 个集合。使用这些集合的文档数据,我创建不同类型的注释并将它们显示在地图视图上。

问题是我想传递存储在每个注释中的所有信息并将其显示在另一个视图控制器上,当您按下标注按钮时会出现。

我想不出一种方法来引用我正在按下的注释,然后将数据传递到另一个屏幕。

这是我第一次使用数据库,我没有太多经验,所以我希望能得到一些帮助。

谢谢!

【问题讨论】:

  • 这不是 Firestore 问题,这是地图问题。
  • @bsod 甚至不确定这是地图问题; 然后将数据传递到另一个屏幕 在您的应用程序中传递数据是一个基本的编码过程。我们真的需要查看您尝试过的代码以及您希望通过什么过程“传递”数据。赛格?代表?子实例?父/子设置?还有什么?请澄清问题并花点时间查看How do I ask a good question?How to create a Minimal, Complete, and Verifiable example

标签: swift firebase google-cloud-firestore mapkit mkannotation


【解决方案1】:

很难给出具体的答案,因为我不知道您的功能的全部范围。但这就是你通常的做法。

首先,当您创建MKAnnotation 子类时,您定义一个属性来保存您可以稍后引用的对象。例如,假设我在地图上显示餐馆和超市。

class RestaurantAnnotation: NSObject, MKAnnotation {
    let restaurant: Restaurant
    
    var title: String? {
        return restaurant.name
    }
    
    var coordinate: CLLocationCoordinate2D {
        return restaurant.coordinate
    }
    
    init(restaurant: Restaurant) {
        self.restaurant = restaurant
        super.init()
    }
}

struct Restaurant {
    let name: String
    let coordinate: CLLocationCoordinate2D
}

超市也是如此。

然后在创建注解时,将Restaurant 对象传递给它。

let restaurant = Restaurant(name: "McDonald's", coordinate: CLLocationCoordinate2D(latitude: 27.2831, longitude: -127.831))
let restaurantAnnotation = RestaurantAnnotation(restaurant: restaurant)
mapView.addAnnotation(restaurantAnnotation)

您实现mapView(_:annotationView:calloutAccessoryControlTapped:) 委托方法,以便在用户点击注释中的标注按钮时收到通知。在其中,您可以轻松引用之前传递给它的对象。

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if let annotation = view.annotation as? RestaurantAnnotation {
        print(annotation.restaurant)
    } else if let annotation = view.annotation as? SupermarketAnnotation {
        print(annotation.supermarket)
    }
}

之后,您可以使用这些数据做任何您想做的事情。在您的情况下,将其传递到新屏幕。

【讨论】:

  • 我可能不理解这个问题,因为它有点含糊,但我认为这个问题是关于在视图控制器之间传递数据 问题是我想传递所有存储的信息在每个注释中并将其显示在另一个视图控制器上不一定将注释添加到特定的视图控制器。
  • @Jay 是的,我同意。似乎 OP 已经弄清楚了显示注释部分,但不知道如何引用每个注释。我在答案中的最后一个代码摘录中展示了如何做到这一点。刚刚添加了显示注释以提供更多上下文。
猜你喜欢
  • 2014-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2011-03-09
相关资源
最近更新 更多