我在Swift 3中建立一个应用程序。
所有接缝都能正常工作但是当我在地图中长按时,它会像是长按两次一样。 我不知道为什么...... 我在长按里面做了一个打印,计算了长按,每次我长按(一次)都会检测到两个长按...为什么会发生这种情况?这有什么不对吗?
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var map: MKMapView!
var numberOfLongPress : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
let latitude: CLLocationDegrees = 38.925560
let longitude: CLLocationDegrees = -9.229723
let lanDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: lanDelta, longitudeDelta: lonDelta)
let coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: coordinates, span: span)
map.setRegion(region, animated: true)
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)))
lpgr.minimumPressDuration = 0.5
map.addGestureRecognizer(lpgr)
}
func longpress(gestureRecognizer: UIGestureRecognizer) {
let touchPoint = gestureRecognizer.location(in: self.map)
let coordinate = map.convert(touchPoint, toCoordinateFrom: self.map)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "My Place"
map.addAnnotation(annotation)
print("longpress activated")
numberOfLongPress = numberOfLongPress + 1
print(numberOfLongPress) //detect number of long presses
}
}
答案 0 :(得分:3)
每次状态更改都会调用选择器,因此您最好检查状态,并在.began
或.ended
上执行您需要执行的操作。
func longpress(gestureRecognizer: UIGestureRecognizer) {
guard gestureRecognizer.state == .began else { return }
// add annotation
}
答案 1 :(得分:2)
让我们打印gestureRecognizer
的状态,您会看到.began
和.ended
。因此,在添加注释之前,请检查gestureRecognizer
的状态。
func longpress(gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer.state == began {
// do something here
}
}