2016-11-12 88 views
0

我有一個代碼在地圖視圖上顯示一些註釋。但是,我試圖在用戶點擊UISwitch按鈕時可以啓用或禁用某些功能。有關我如何實現這一目標的任何建議?提前致謝!Swift:如何啓用和禁用地圖視圖上的註釋?

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?... 
    } 
+0

你只需要刪除註釋 – Paulw11

+0

我有一個代碼,刪除註釋,但是如果我想的註解重新出現,有沒有簡單的方法來做到這一點? – Geniouse

+0

只需重新添加它們?這是一個非常簡單的過程來添加和刪除它們 – Paulw11

回答

2

使用viewFor(annotation : MKAnnotation)方法:

斯威夫特3

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

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

非常感謝你......這個伎倆! – Geniouse

相關問題