regiondidchange called several times on app load swift

好久不见. 提交于 2019-12-12 09:26:49

问题


I have a map that when i pan away or type in a location and navigate to it that I want a simple print function to run. I have this accomplished, however, when i first load the app it calls that print function several times until it is finished zooming in. Is there a way to NOT count the initial on app load region change?


回答1:


answer finally found herehttp://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
}
}



回答2:


Here's a Swift 4.2 answer that's more concise.

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()
    }
}


来源:https://stackoverflow.com/questions/33131213/regiondidchange-called-several-times-on-app-load-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!