iOS - 添加和删除 MKCircle 覆盖到 MapView 导致故障

iOS -Adding and Removing MKCircle Overlay to MapView causing glitch

我有一个 MapView,用户可以 select 显示一个区域的半径。我添加了一个 MKCircle 作为覆盖。当半径从 30 英里变为 1 英里时,在 MapView 放大时 MKCircle 的周边出现明显的故障。故障看起来有点像天赋。它仅在放大而不缩小时发生。\

由于缩放不断变化,我在添加另一个覆盖之前删除了旧覆盖,但我认为这不是问题所在。

如何消除 MapView 缩放变化时圆上的故障?

@IBAction func newRadiusButtonTapped(sender: UIButton) {

    // coordinate is the users location and span was 10 miles now it's 1 mile
    let region = MKCoordinateRegionMake(location.coordinate, span)
    mapView.setRegion(region, animated: true)

    let circle = MKCircle(center: location.coordinate, radius: radius)

     // remove old overlay before adding another one
     for overlay in mapView.overlays {
         mapView.remove(overlay)
     }

     view.layoutIfNeeded()
     // mapView.layoutIfNeeded() I tried this but it didn't make a difference
     mapView.add(circle)
}

我找不到导致故障的原因,但我在 mapView 上找到了这个委托方法 from this answer,它会在 mapView 区域完成更改后收到通知。我在那里添加叠加层

func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { 
}

流程简单:

我创建了一个 属性 类型的圆圈 MKCircle? 我还创建了名为 属性 的 Bool 类型的 shouldAddCircle 并将其设置为 true。 按下按钮时,我用在按钮内创建的 MKCircle 初始化圆圈 属性,并将 shouldAddCircle 设置为 true。 在按钮功能中,我删除了所有 mapViews 叠加层。

在委托方法中,我现在检查 shouldAddCircle 属性 是否为真,如果是,然后检查以确保圆圈 属性 不为零。如果它们匹配,那么我将初始化的圆圈添加到 mapView。在我将圆圈添加到 mapView 之后,我必须将 shouldAddCircle 设置为 false,因为每次用户滚动地图时 regionDidChangeAnimated 都会被调用,并且它会继续向地图添加叠加层。

这是'下面的代码。请务必在 viewDidLoad 中添加 mapView.delegate = self 并在所有内容之前设置 MKMapViewDelegate

var circle: MKCircle?
var shouldAddCircle = true

@IBAction func newRadiusButtonTapped(sender: UIButton) {

    // coordinate is the users location and span was 10 miles now it's 1 mile
    let region = MKCoordinateRegionMake(location.coordinate, span)
    mapView.setRegion(region, animated: true)

    let circle = MKCircle(center: location.coordinate, radius: radius)

    // set the circle property to match the circle that was just created
    self.circle = circle

    // set this true
    shouldAddCircle = true

    // remove old overlay before adding another one
    for overlay in mapView.overlays {
        mapView.remove(overlay)
    }
}

// this function gets called repeatedly as the mapView is zoomed and/or panned
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {

    // make sure this is true because that means the user updated the radius
    if shouldAddCircle {

       // make sure the circle isn't ni
       if let circle = self.circle {
           // after the mapView finishes add the circle to it
           mapView.add(circle)

           // set this to false so that this doesn't called again until the user presses the button where they set it to true
           shouldAddCircle = false
       }
    }
}