我有自定義視圖,當用戶點擊註釋時出現,但我不知道如何在用戶點擊地圖上的其他位置時使這些視圖消失。 在Google Map SDK for iOS中,它會是didTapAtCoordinate
,然後我會設置view.hidden = true
。如何在用戶使用MapKit在地圖上點擊時執行操作Swift
我認爲可以用touchBegan
來完成,雖然我之前沒有使用過這個功能嗎?雖然我更喜歡MapKit版本的Google谷歌didTapAtCoordinate
。
編輯
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var myCustomView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
myCustomView.hidden = true
//MyAnnatationClass is my class where I store MKAnnatations with additional details
let ann = MyAnnatationClass(coordinate: CLLocationCoordinate2D(latitude: 54.694084, longitude: 25.288782), title: "DEMO2", name: "Some Name")
mapView.addAnnotation(ann)
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "id"
if annotation.isKindOfClass(MyAnnatationClass.self) {
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.image = UIImage(named: "pin.png")
annotationView!.canShowCallout = true
} else {
annotationView!.annotation = annotation
}
return annotationView
}
return nil
}
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
//Set view details
let myAnn = view.annotation as! MyAnnatationClass
someViewLabel.text = myAnn.name
myCustomView.hidden = false
let annotationTap = UITapGestureRecognizer(target: self, action: "tapRecognized:")
annotationTap.numberOfTapsRequired = 1
view.addGestureRecognizer(annotationTap)
let selectedAnnotations = mapView.selectedAnnotations
for annotationView in selectedAnnotations{
mapView.deselectAnnotation(annotationView, animated: true)
}
}
func mapView(mapView: MKMapView, didDeselectAnnotationView view: MKAnnotationView) {
view.hidden = true
}
func tapRecognized(gesture:UITapGestureRecognizer){
let selectedAnnotations = mapView.selectedAnnotations
for annotationView in selectedAnnotations{
mapView.deselectAnnotation(annotationView, animated: true)
}
}
}
目前,當我觸摸註釋,myCustomView
出現和註釋消失。如果在didDeselectAnnotationView
中我將view
更改爲myCustomView
,則自定義視圖不會顯示。
嘗試製作一個布爾標誌,就像我在我的回答中提到的那樣。你可以檢查isShow並根據標誌切換隱藏 – MisterGreen