问题
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