iOS-向MapView添加和删除MKCircle叠加层会导致故障

时间:2018-11-03 18:29:18

标签: ios swift mkmapview mkcircle

我有一个MapView,用户可以选择一个半径来显示一个区域。我添加一个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)
}

30 miles

glitch

1 mile

1 个答案:

答案 0 :(得分:0)

我找不到引起故障的原因,但是我在mapView上找到了此委托方法from this answer,该方法在mapView区域完成更改后得到了通知。我在上面添加覆盖物

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

简单的过程:

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

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

这是下面的代码。确保在mapView.delegate = self中添加viewDidLoad,并在所有内容之前设置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
       }
    }
}