Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement iOS 11's MKUserTrackingButton

I'm trying to implement a MKUserTrackingButton (which is new in iOS 11 SDK). This "button" actually inherits from UIView so I just put a UIView instance on my Map and in the Identity Inspector, linked it to the MKUserTrackingButton class, added an outlet in my code and in viewDidLoad().

I initialize it the following way:

self.centerMapButton = MKUserTrackingButton.init(mapView: self.mapView)

However, nothing works, I just have a blank view on my Map.

PS: Here's the WWDC 2017 session about this new feature (at 1:25): https://developer.apple.com/videos/play/wwdc2017/237/

Here's the method I call in viewDidLoad() to implement the button:

func setupUserTrackingButtonAndScaleView() {
    mapView.showsUserLocation = true

    let button = MKUserTrackingButton(mapView: mapView)
    button.layer.backgroundColor = UIColor(white: 1, alpha: 0.8).cgColor
    button.layer.borderColor = UIColor.white.cgColor
    button.layer.borderWidth = 1
    button.layer.cornerRadius = 5
    button.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(button)

    let scale = MKScaleView(mapView: mapView)
    scale.legendAlignment = .trailing
    scale.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(scale)

    NSLayoutConstraint.activate([button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10),
                                 button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
                                 scale.trailingAnchor.constraint(equalTo: button.leadingAnchor, constant: -10),
                                 scale.centerYAnchor.constraint(equalTo: button.centerYAnchor)])
}

Note that I have a mapView instance in my ViewController, of course.

like image 499
Florian P. Avatar asked Oct 16 '17 09:10

Florian P.


1 Answers

I just ran your code against my MapKit app and it worked fine. Make sure you are passing the proper mapView instance to the MKUserTrackingButton.

like image 135
DouglasHeitner Avatar answered Nov 05 '22 18:11

DouglasHeitner