swiftmkmapviewhybrid

Change map type (hybrid, satellite) via segmented control


I am trying to change the map type using a segmented control button, I wish for it to change the type of the map with 3 options: Standard, Satellite and Hybrid. So far I have this code but nothing happens once a different map type is selected:

@IBAction func segmentedControlAction(sender: UISegmentedControl!) {

    if sender.selectedSegmentIndex == 0{

        mapView.mapType = MKMapType.Standard
    }
    else if sender.selectedSegmentIndex == 1{

        mapView.mapType = MKMapType.Satellite
    }
    else if sender.selectedSegmentIndex == 3{

        mapView.mapType = MKMapType.Hybrid
    }
}

I am new to Swift and Xcode so any help is appreciated :)

Thanks


Solution

  • First, ensure that your method is being called when the segmented control selection changes. It's easy to forget to hook up outlet methods. Once you've verified that, remember that map data is loaded asynchronously, so you may not see it change immediately after selecting a different mode. However, with the code you posted, you'll never see the .Hybrid type because the selectedSegmentIndex in a 3-segment control will never be 3.

    A more concise way of implementing this method is:

    @IBAction func segmentedControlAction(sender: UISegmentedControl!) {
        switch (sender.selectedSegmentIndex) {
            case 0:
                mapView.mapType = .Standard
            case 1:
                mapView.mapType = .Satellite
            default:
                mapView.mapType = .Hybrid
        }
    }
    

    Note that Swift doesn't need break statements at the end of each case.

    Edit: Swift 4.1

    @IBAction func mapTypeSegmentSelected(_ sender: UISegmentedControl) {
            switch sender.selectedSegmentIndex {
            case 0:
                mapView.mapType = .standard
            case 1:
                mapView.mapType = .satellite
            default:
                mapView.mapType = .hybrid
            }
        }