Silver Challenge: UIButton with location arrow icon?

Rather than a button that says “Location”, I would like to have a button that uses the actual iOS arrow that is used in Apple Maps for prompting to show the user’s location. This isn’t a built-in emoji though, how do I get the button to show that up-right arrow instead?
This icon:

Your answer is here:

Download the MapKit Sample linked on that page, which gives you a copy of what Apple put together for WWDC’17 for a fake app called TANDM. It has the code you are looking for in it, which is basically as follows:

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
    let scale = MKScaleView(mapView: mapView)
    scale.legendAlignment = .trailing
    scale.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -55),
                                 button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
                                 scale.trailingAnchor.constraint(equalTo: button.leadingAnchor, constant: -10),
                                 scale.centerYAnchor.constraint(equalTo: button.centerYAnchor)])

The only thing I changed from the Apple implementation of this code is the bottomAnchor layout contraint. I had to move that up to “-55” so that it was not hidden by the tab bar controller. I’m sure there’s a way to anchor off of the top of the tab bar controller, but I don’t know how.

Once you have that function in place, you then just need to call the function after your map and segmented control have been loaded and displayed.

You also have to implement the code to turn on Core Location so that the app will get information about the user’s location. First, you need to “import CoreLocation” at the top. Second, create a Location Manager:

// Create a location manager to trigger user tracking
let locationManager: CLLocationManager = {
    let manager = CLLocationManager()
    return manager

I’m not a huge fan of closures, but that’s how Apple did it, and I copied it. :wink:

Third, you need to go into the app’s info Plist and add a requirement that the app seek the user’s permission to know the user’s location. This video explains that part the best:

This code does not yet “zoom” to the user’s location.

1 Like