如何禁止在MKMapView上旋转但显示标题?

时间:2014-08-13 15:08:11

标签: swift mkmapview

对于我的项目,我想在没有旋转地图的情况下(用蓝色圆锥体)将MKMapView放在用户的标题上。

enter image description here

Here's a gist

此外,启用mapView.setUserTrackingMode(MKUserTrackingMode.FollowWithHeading, animated: true)后,我无法浏览地图。

我尝试在trackingMode上设置mapView:didChangeUserTrackingMode,但它无效。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,并使用CLLocationManagerlocationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading)方法解决了这个问题:

class MyViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!
    weak var userAnnotationView: MKAnnotationView?
    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.showsUserLocation = true
        mapView.delegate = self
        locationManager.delegate = self
        locationManager.startUpdatingHeading()
    }
}

// MARK: - MKMapViewDelegate
extension MyViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if let annotation = annotation as? MKUserLocation {
            // User
            let reuseIdentifier = "UserAnnotationView"
            let annotationView: MKAnnotationView
            if let view = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) {
                annotationView = view
            } else {
                annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
            }
            annotationView.image = UIImage(named: "userLocationWithoutHeading")
            userAnnotationView = annotationView
            return annotationView
        } else {
            return nil
        }
    }
}

// MARK: - CLLocationManagerDelegate
extension MyViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        guard let userAnnotationView = userAnnotationView else { return }
        userAnnotationView.image = UIImage(named: "arrowUp")
        let rotationAngle = heading.magneticHeading * Double.pi / 180.0
        userAnnotationView.transform = CGAffineTransform(rotationAngle: CGFloat(rotationAngle))
    }
}