它有一个程序生成的手势识别器。
问题是,偶尔,点击注释,也(或相反)进入地图。
我附上了演示,归结为一个丑陋的,简单的ViewController(看截图,看看它看起来像什么)。
如果你用它创建了一个应用程序,然后在底部的正方形上反复单击/点击(它们在单击/点击时改变颜色),地图就会放大。
防止注释下的手势识别器在注释中获取事件(甚至双击)的最佳方法是什么?
把你的眼睛藏起来。这会很有趣:
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let washingtonMonument = CLLocationCoordinate2D(latitude: 38.8895, longitude: -77.0353)
let annotation = GestureAnnotation()
annotation.coordinate = washingtonMonument
self.mapView.addAnnotation(annotation)
let washingtonRegion = MKCoordinateRegion(center: washingtonMonument, span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
self.mapView.setRegion(washingtonRegion, animated: false)
}
func mapView(_ inMapView: MKMapView, viewFor inAnnotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = inAnnotation as? GestureAnnotation {
return annotation.viewObject
}
return nil
}
}
class GestureTargetView: UIView {
let colors = [UIColor.red, UIColor.yellow, UIColor.black, UIColor.green]
var tapGestureRecognizer: UITapGestureRecognizer?
var currentColorIndex = 0
override func layoutSubviews() {
if nil == self.tapGestureRecognizer {
self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(type(of: self).handleTap))
self.addGestureRecognizer(self.tapGestureRecognizer!)
}
self.backgroundColor = self.colors[0]
}
@objc func handleTap(sender: UITapGestureRecognizer) {
if .ended == sender.state {
self.currentColorIndex += 1
if self.currentColorIndex == self.colors.count {
self.currentColorIndex = 0
}
self.backgroundColor = self.colors[self.currentColorIndex]
}
}
}
class GestureAnnotationView: MKAnnotationView {
var gestureView: GestureTargetView!
override func prepareForDisplay() {
self.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 128, height: 128))
if nil == self.gestureView {
self.gestureView = GestureTargetView(frame: self.frame)
self.addSubview(self.gestureView)
}
super.prepareForDisplay()
}
}
class GestureAnnotation: NSObject, MKAnnotation {
var myView: GestureAnnotationView!
var coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
var viewObject: MKAnnotationView! {
get {
if nil == self.myView {
self.myView = GestureAnnotationView(annotation: self, reuseIdentifier: "")
}
return self.myView
}
}
}