我找不到导致故障的原因,但我从 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
并设置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
}
}
}