Swift:如何在地图视图上启用和禁用注释?

时间:2016-11-12 23:22:04

标签: ios swift xcode xcode7

我有一个代码,可以在地图视图上显示一些注释。但是,我试图在用户点击UISwitch按钮时启用或禁用某些功能。关于我如何实现这一目标的任何建议?提前谢谢!

 let theHouse = MKPointAnnotation()
        theHouse.coordinate = CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365)

    theHouse.title = "The House, DC"
        theHouse.subtitle = "New Jersey, DC"

    myMapView.addAnnotation(theHouse)
    myAnnotations.append(theHouse.title!)

    //Switch that toggles the annotation...
    @IBAction func turnOffAnnotations(_ sender: UISwitch) {
    //Code that enables and disables the annotation?

if toggle.isOn{
    let visible = myMapView.visibleMapRect
    let inRect = myMapView.annotations(in: visible)

    for annotation: MKAnnotation in myMapView.annotations{
        if (inRect.contains(anno as! AnyHashable)){
          myMapView.removeAnnotation(annotation)
        }
    }
    } else {
        let visible = myMapView.visibleMapRect
        let inRect = myMapView.annotations(in: visible)

        for annotation: MKAnnotation in myMapView.annotations{
            if (inRect.contains(anno as! AnyHashable)){
                myMapView.addAnnotation(annotation)
            }
        }
    }
//How to add back the removed annotations here?...
    }

1 个答案:

答案 0 :(得分:6)

使用viewFor(annotation : MKAnnotation)方法:

Swift 3

@IBAction func changeAnnotationsVisibility(_ sender: UISwitch) {
    let annotationVisible = sender.isOn

    for annotation in myMapView.annotations {
        myMapView.view(for: annotation)?.isHidden = !annotationVisible
    }
}