iOS Tutorials: Changing MapKit Layout

On this tutorials, we will make a button that could change the layout of the map by tapping on the button. This tutorial will simply be implementing an UIButton that contains the function to change layout.

On your Xcode, go to File > New > Project to create a new blank project.

Go ahead and give your project any name. For mine, I put Map. You could go ahead and put in the required information as your own information.

Go to your Main.storyboard and pick up the required object. We will be needing Map Kit View and Button for this project. Make sure your Map Kit View is stretch out like mine and the button is placed below the map.

Now that we are done with Main.storyboard, we need to connect Map Kit View and the Button to the ViewController.swift. There is an easy way to pop out the code section. Look on the top right where you could see two circle, press that and ViewController.swift will pop up. This easily allow you to multitask.

Now drag Control + Drag MKMapView to the ViewController.swift and give it a name which in my case is named mapView.

Then Control + Drag the button the ViewController.swift and change the connection to Action and the type to UIButton. We will be keeping track of the clicks on the UIButton by adding UIButton as the type. You can name it anything you want, but I am naming it changeLayout.

You’ll probably see some error on the line of mapView, that is because we need to import a module. Make sure you import the MapKit and when you insert this line of code, the error will disappear.

import MapKit

Now the next thing to do is to configure the changeLayout. We want it to be able to change the layout of the map every time we pressed on it.

@IBAction func changeLayout(_ sender: UIButton) {  
     sender.tag += 1
     if sender.tag > 2 {
          sender.tag = 0
      switch sender.tag {
       case 1 :
          mapView.mapType = .satellite
       case 2:
          mapView.mapType = .standard
          mapView.mapType = .hybrid

The code above basically explains that each time we click on the button, it will increase its tag number by 1, however if the tag goes more than 2, it will reset back to 0. The following code is the key part in changing the layout of the map, it will change the layout of the map each time we clicked on it. When you run your project, hopefully it will look like this.

The project is uploaded to GitHub and to view the animated version, go to GitHub

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *