【问题标题】:Adding a custom MKAnnotationView to a MKPointAnnotation将自定义 MKAnnotationView 添加到 MKPointAnnotation
【发布时间】:2015-04-18 02:56:21
【问题描述】:

我正在尝试使用 swift 创建一个 iOS 应用程序,该应用程序在地图视图上创建注释。但是,在大多数情况下,我都在尝试创建一个自定义视图,当用户点击图钉时会弹出该视图。这是放置注释的代码:

    let point = MKPointAnnotation()

    //This isn't the actual location
    let location = CLLocationCoordinate2DMake(1, 1)

    point.coordinate = location
    point.title = "Title"
    point.subtitle = "Description"
    map.addAnnotation(point)
    map.centerCoordinate = point.coordinate

    let mapCamera = MKMapCamera()
    mapCamera.centerCoordinate = location
    mapCamera.altitude = 300
    mapCamera.heading = 180

    self.map.camera = mapCamera

此代码将图钉放置在正确的位置。但是,假设我有一个红色背景的 MKAnnotationView 对象,如下所示:

let pointDesc = MKAnnotationView()
pointDesc.backgroundColor = UIColor.redColor()

如何将该视图添加到 MKPointAnnotation。最初我认为map.addSubview(pointDesc) 会起作用。但事实并非如此。

有人有什么建议吗?

【问题讨论】:

    标签: ios swift maps mkannotationview


    【解决方案1】:

    您需要在自己设计该视图的地方实现viewForAnnotation。这是我的应用程序中的代码 sn-p,它创建了一个带有红色删除按钮的简单视图。您可能会了解如何根据您的需要实现它:

    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {   
        if annotation is PinAnnotation {  // PinAnnotation is my custom annotation class
            let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")
    
            pinAnnotationView.pinColor = .Purple
            pinAnnotationView.draggable = true
            pinAnnotationView.canShowCallout = true
            pinAnnotationView.animatesDrop = true
    
            let deleteButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
            deleteButton.frame.size.width = 44
            deleteButton.frame.size.height = 44
            deleteButton.backgroundColor = UIColor.redColor()
            deleteButton.setImage(UIImage(named: "trash"), forState: .Normal)
    
            pinAnnotationView.leftCalloutAccessoryView = deleteButton
    
            return pinAnnotationView
        }
    
        return nil
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 2012-11-30
      • 2020-10-25
      • 1970-01-01
      相关资源
      最近更新 更多