我创建了一个地图,右上角有一个用户跟踪按钮。我想知道如何在加载时默认将状态设置为"跟随头灯",以便它像您在 GPS 上一样跟随用户的当前位置?
加载时的当前行为:按钮当前行为
加载时的期望行为:按钮期望的行为
代码片段:
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)
}
// ...
}