对长按手势执行多项操作
Multiple actions being performed on Long Press Gesture
我正在尝试在长按期间执行某个操作(目前,我只是打印出数据)。但是每当我在 simulator/phone 中做长按手势时,它都会重复这个动作几次。每当激活长按手势时,如何让它只执行一次操作?
抱歉,我是 iOS 开发的新手。
这是我的代码:
@IBAction func addRegion(_ sender: Any) {
guard let longPress = sender as? UILongPressGestureRecognizer else
{ return }
let touchLocation = longPress.location(in: mapView)
let coordinate = mapView.convert(touchLocation, toCoordinateFrom: mapView)
let region = CLCircularRegion(center: coordinate, radius: 50, identifier: "geofence")
mapView.removeOverlays(mapView.overlays)
locationManager.startMonitoring(for: region)
let circle = MKCircle(center: coordinate, radius: region.radius)
mapView.add(circle)
print(coordinate.latitude)
print(coordinate.longitude)
//returns:
// 27.4146234860156
// 123.172249486142
// ... (a lot of these)
// 27.4146234860156
// 123.172249486142
}
手势识别器函数以其当前状态调用多次。
如果您想在长按手势激活时执行某些操作
您应该像下面这样对手势状态应用验证:
guard let longPress = sender as? UILongPressGestureRecognizer else
{ return }
if longPress.state == .began { // When gesture activated
}
else if longPress.state == .changed { // Calls multiple times with updated gesture value
}
else if longPress.state == .ended { // When gesture end
}
我正在尝试在长按期间执行某个操作(目前,我只是打印出数据)。但是每当我在 simulator/phone 中做长按手势时,它都会重复这个动作几次。每当激活长按手势时,如何让它只执行一次操作?
抱歉,我是 iOS 开发的新手。
这是我的代码:
@IBAction func addRegion(_ sender: Any) {
guard let longPress = sender as? UILongPressGestureRecognizer else
{ return }
let touchLocation = longPress.location(in: mapView)
let coordinate = mapView.convert(touchLocation, toCoordinateFrom: mapView)
let region = CLCircularRegion(center: coordinate, radius: 50, identifier: "geofence")
mapView.removeOverlays(mapView.overlays)
locationManager.startMonitoring(for: region)
let circle = MKCircle(center: coordinate, radius: region.radius)
mapView.add(circle)
print(coordinate.latitude)
print(coordinate.longitude)
//returns:
// 27.4146234860156
// 123.172249486142
// ... (a lot of these)
// 27.4146234860156
// 123.172249486142
}
手势识别器函数以其当前状态调用多次。 如果您想在长按手势激活时执行某些操作
您应该像下面这样对手势状态应用验证:
guard let longPress = sender as? UILongPressGestureRecognizer else
{ return }
if longPress.state == .began { // When gesture activated
}
else if longPress.state == .changed { // Calls multiple times with updated gesture value
}
else if longPress.state == .ended { // When gesture end
}