regiondidchange在app load swift上多次调用

时间:2015-10-14 16:51:09

标签: ios xcode swift mapkit swift2

我有一张地图,当我平移或输入位置并导航到它时,我想要一个简单的打印功能运行。我已经完成了这项工作,但是,当我第一次加载应用程序时,它会多次调用该打印函数,直到完成放大。有没有办法不计算应用程序加载区域更改的初始值?

2 个答案:

答案 0 :(得分:3)

答案终于在这里找到了http://ask.ttwait.com/que/5556977

private var mapChangedFromUserInteraction = false

private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view = self.mapView.subviews[0]
//  Look through gesture recognizers to determine whether this region change is from user interaction
if let gestureRecognizers = view.gestureRecognizers {
    for recognizer in gestureRecognizers {
        if( recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended ) {
            return true
        }
    }
}
return false
}

func mapView(mapView: MKMapView, regionWillChangeAnimated animated:    
Bool) {
mapChangedFromUserInteraction =   
mapViewRegionDidChangeFromUserInteraction()
if (mapChangedFromUserInteraction) {
    // user changed map region
}
}

func mapView(mapView: MKMapView, regionDidChangeAnimated animated:   
Bool) {
if (mapChangedFromUserInteraction) {
    // user changed map region
}
}

答案 1 :(得分:0)

这是一个Swift 4.2的答案,更加简洁。

private var mapChangedFromUserInteraction = false

public func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    if (mapChangedFromUserInteraction) {
       // do something
    }
}

private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
    return map.subviews.first?.gestureRecognizers?
        .contains(where: {
            $0.state == .began || $0.state == .ended
        }) == true
}

public func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
    if !mapChangedFromUserInteraction { // I only wanted to check until this was true
        mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()
    }
}