0

我有一个 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 英里

毛刺

1 英里

4

1 回答 1

0

我找不到导致故障的原因,但我从 mapView 上的这个答案中找到了这个委托方法,该方法在 mapView 区域完成更改后得到通知。我在那里添加叠加层

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

简单的过程:

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

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

这是下面的代码。一定要在一切之前添加mapView.delegate = self并设置viewDidLoadMKMapViewDelegate

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
       }
    }
}
于 2018-11-03T23:37:59.593 回答