如何设置Mapkit用户跟踪按钮状态

How to set Mapkit user tracking button state

我创建了一个右上角带有用户跟踪按钮的地图。我想知道如何在加载时将状态默认设置为 "followWithHeadlights",以便它像在 GPS 上一样跟随用户当前位置?

当前负载行为: Button current behaviour

加载时的期望行为: Button desired behaviour

代码片段:

func setUserTrackingButton() {

    // Mapkit tracking button
    let trackingButton: MKUserTrackingBarButtonItem = MKUserTrackingBarButtonItem.init(mapView: mapView)
    trackingButton.customView?.tintColor = UIColor(red:0.01, green:0.81, blue:0.37, alpha:1.0)
    trackingButton.customView?.frame.size = CGSize(width: 50, height: 50)

    let toolBarFrame = CGRect(origin: CGPoint(x: 0, y: 0) , size: CGSize(width: 50, height: 50))
    let toolbar = UIToolbar.init(frame: toolBarFrame)
    toolbar.barTintColor = UIColor.white
    toolbar.isTranslucent = true
    let flex: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
    toolbar.items = [flex, trackingButton, flex]

    let origin = CGPoint(x: self.view.frame.size.width - 85, y: 60)
    let roundedSquare: UIView = UIView(frame: CGRect(origin: origin, size: CGSize(width: 50, height: 50)))
    roundedSquare.backgroundColor = UIColor.white
    roundedSquare.layer.cornerRadius = 5
    roundedSquare.layer.masksToBounds = true

    roundedSquare.addSubview(toolbar)
    mapView.addSubview(roundedSquare)
}

ViewDidLoad 包括:

mapView.setUserTrackingMode(MKUserTrackingMode.followWithHeading, animated: true)

谢谢!

必须在地图视图完全加载后设置用户跟踪模式。 viewDidLoad 情况并非如此。

您可以使用 MKMapViewDelegate 方法 mapViewDidFinishLoading(mapView:) 了解地图何时加载:

class MyMapViewController: UIViewController, MKMapViewDelegate {

    // ...

    override func viewDidLoad() {        
        super.viewDidLoad()

        // ...
        mapView.delegate = self
    }

    // ...

    func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
        mapView.setUserTrackingMode(.followWithHeading, animated: true)
    }

    // ...

}