如何 stop/remove 选择一个 UISwitch 关闭时的方法? swift5/xcode11

how to stop/remove a method when selecting a UISwitch to off? swift5/xcode11

我正在开发一个带有一些叠加层(注释、圆圈、多边形)的地图应用程序。我也有 appear/disappear 它们的 UISwitch。因为注释很简单:.add / .remove,它有效。

@IBAction func airportLayerSwitch(_ sender: UISwitch) {

    if sender.isOn {
        mapView.addAnnotations(airports)
    } else {
        mapView.removeAnnotations(airports)
    }
}

但是对于圆,多边形我不能让它们消失。这是我的圈子功能:

func airportBoundryOverlay(airportName:String, radius:CLLocationDistance){

    for airport in airports {
        if airport.title == airportName{
            let center = airport.coordinate
            let circle = MKCircle(center: center, radius: radius)
            mapView.addOverlay(circle)
        }
    }
}

func airportBoundries() {
    
    airportBoundryOverlay(airportName: "Békéscsaba",radius: 4000)
    airportBoundryOverlay(airportName: "Budaörs",radius: 4000)
}

所以对于我的第二个 UISwitch:

@IBAction func tizLayerSwitch(_ sender: UISwitch) {

    if sender.isOn {
        airportBoundries()
    } else {
        // TODO: ??????? disappear airportBoundries() ??????
    }
}

当我打开 UISwitch 时,圆圈出现了,但我无法让它们消失。

您可以使用 MKMapView.removeOverlays 调用来执行此操作。

var circleOverlays: [MKOverlay] = []

func airportBoundryOverlay(airportName: String, radius: CLLocationDistance) {
    for airport in airports {
        if airport.title == airportName{
            let center = airport.coordinate
            let circle = MKCircle(center: center, radius: radius)
            mapView.addOverlay(circle)

            // Collect the circle overlays here
            circleOverlays.append(circle)
        }
    }
}

@IBAction func tizLayerSwitch(_ sender: UISwitch) {
    if sender.isOn {
        airportBoundries()
    } else {
        mapView.removeOverlays(circleOverlays)
        circleOverlays = []
    }
}