在 Swift 中的同一个 mapView 中分配多个注释 pinColors?

Posted

技术标签:

【中文标题】在 Swift 中的同一个 mapView 中分配多个注释 pinColors?【英文标题】:Assigning multiple annotation pinColors within the same mapView in Swift? 【发布时间】:2015-04-28 19:17:07 【问题描述】:

所以我有一个地图视图,其中添加了用户在不同位置发布的注释。我正在尝试将引脚颜色更改为绿色、红色或紫色,具体取决于引脚创建后的时间。

我在这里遇到的问题是所有引脚都希望更改为一种指定的颜色,而不是显示具有不同颜色的引脚。我似乎无法弄清楚这里出了什么问题。使用下面的示例代码,它将所有引脚设置为绿色,而实际上只有不到 4 小时前创建的引脚应该是绿色的引脚,红色引脚超过 4 小时但小于 44 小时,紫色引脚较旧超过 44 小时。

感谢任何帮助!

pinColorQuery.findObjectsInBackgroundWithBlock 
            (dateCreated, error) -> Void in
            if error == nil 
                // The find succeeded.

                let createdDates = dateCreated as! [PFObject]

                for date in createdDates 
                    let createdAt = date.createdAt as NSDate!
                    let currentDate = NSDate()
                    let expirationDate = currentDate.timeIntervalSinceDate(date.createdAt!)

                    //This is where I attempt to set the pinColor based on age of pin
                    if (expirationDate < 18000) 
                        normalPinView!.pinColor = .Green
                     else if (expirationDate < 162000) 
                        normalPinView!.pinColor = .Red
                     else if (expirationDate > 162050) 
                        normalPinView!.pinColor = .Purple
                    

                

             else 
                // Log details of the failure
                println("Error: \(error!) \(error!.userInfo!)")
            
        

expirationDate 间隔返回正确,我用一个简单的println("\(expirationDate)") 进行了检查。

【问题讨论】:

【参考方案1】:

我在 mapview 上使用过相同类型的功能,但使用的是 Objective-c。这不会直接更改已添加注释的引脚颜色。解决方法是以某种方式枚举所有注释并应用 pincolor 的逻辑,如果 pincolor 发生变化,则使用新 pincolor 创建新注释但使用旧数据源,然后删除旧注释并在同一位置添加新注释。就个人而言,它肯定会起作用,并且是实际的解决方案。在我的应用程序中,如果帖子的评论数超过 10,50 等等,我会更改图钉颜色和图钉大小。

Objective-c 代码:在某个函数中。

for (int i =0; i < [self.mapView.annotations count]; i++)

   if ([[self.mapView.annotations objectAtIndex:i] isKindOfClass:[CustomAnnotation class]])

     CustomAnnotationClass *annotation=[self.mapView.annotations objectAtIndex:i];

    if (annotation.expirationDuration <= 18000)
     
         CustomAnnotationClass *newAnnotation = annotation;
         newAnnotation.pinColor = purple;
         [self.mapView removeAnnotation:[self.mapView.annotations objectAtIndex:i]];
         [self.mapView addAnnotation:newAnnotation];
      

      

这只是一个粗略的想法,会出现拼写错误,而且不是swift,而是for循环你可以使用枚举。

【讨论】:

好的,我有点理解你的意思,但我很困惑我是如何将它实际放入代码中的? @Zach 我已经编辑了我的答案,它包含一些粗略的代码。如果您不明白,请告诉我,我会尽快为您提供。 你能用 Swift 提供它吗?这让我很困惑:(

以上是关于在 Swift 中的同一个 mapView 中分配多个注释 pinColors?的主要内容,如果未能解决你的问题,请参考以下文章

从 Swift 字典中分配 UITableView Cell 标签文本

Swift 没有从 JSON 结果中分配变量

Firebase:保留在observeSingleEvent中分配的值[重复]

在文本字段中分配和辞职第一响应者

如何在 Swift 3 中的 mapview 上生成不同的图钉?

为啥在单个语句中分配动态对象的成员变量会导致 PHP 中的语法错误?