Swift - MapView间歇性地将注释标题/副标题显示为空白

时间:2018-02-04 00:10:56

标签: swift mkmapview mkannotation

我的iOS地图视图显示了初始注释。我希望用户能够点击地图并将注释移动到用户点击的位置,但是要在注释中保留非坐标信息(例如标题,副标题)。下面的代码有效,但间歇性地没有显示标题和副标题(请参阅动画并且名称“Spot Name”有时不显示)。我不清楚为什么会这样。如果我在mapView.addAnnotation之后添加print语句来打印spot.name和spot.title,那么String值就在那里。在MKAnnotation符合类中保持不变。此外,当我单击标记时,标注中显示正确的标题和副标题,即使它们没有显示在注释中。感谢任何建议/更正。谢谢!

import UIKit
import MapKit

class SpotDetailViewController: UIViewController {
    @IBOutlet weak var mapView: MKMapView!
    var spot: Spot! // Spot class conforms to NSObject & MKAnnotation

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate = self
        spot = Spot()
        spot.coordinate = CLLocationCoordinate2D(latitude: 42.334709, longitude: -71.170061)
        spot.name = "Spot Name"
        spot.address = "Spot Address, Spot Town, Spot State"

        // Set initial region
        let regionDistance: CLLocationDistance = 250
        let region = MKCoordinateRegionMakeWithDistance(spot.coordinate, regionDistance, regionDistance)
        mapView.setRegion(region, animated: true)
        mapView.addAnnotation(self.spot)
    }


    @IBAction func mapViewTapped(_ sender: UITapGestureRecognizer) {
        let annotationView = mapView.view(for: mapView.annotations[0])
        let touchPoint = sender.location(in: mapView)
        guard !(annotationView?.frame.contains(touchPoint))! else {
            return
        }
        let newCoordinate: CLLocationCoordinate2D = mapView.convert(touchPoint, toCoordinateFrom: mapView)
        spot.coordinate = newCoordinate
        mapView.removeAnnotations(mapView.annotations)
        mapView.addAnnotation(self.spot)
        mapView.setCenter(spot.coordinate, animated: true)
    }
}

extension SpotDetailViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        let identifer = "Marker"
        var view: MKMarkerAnnotationView
        if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifer) as? MKMarkerAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifer)
            view.canShowCallout = true
            view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
        }
        return view
    }
}

enter image description here

0 个答案:

没有答案