Adam Adam - 2 months ago 10
Swift Question

Swift Buttonaction Text Change

Trying to make the text change when its pressed and shows different type of map (Hybrid, standard or satellite).
But when i press the button i get error (well, not when i don't have the "textchange" code in it). So how do i make the text change when it knows its different type of map without getting this error and crashing the app...?

i use this code

@IBAction func mapType(sender: AnyObject) {
if Mapview.mapType == MKMapType.Standard {
Mapview.mapType = MKMapType.Satellite
sender.setTitle("Satellite", forState: .Normal)

} else {
if Mapview.mapType == MKMapType.Satellite {
Mapview.mapType = MKMapType.Hybrid
sender.setTitle("Hybrid", forState: .Normal)

} else {
Mapview.mapType = MKMapType.Standard
sender.setTitle("Standard", forState: .Normal)
}
}
}

Answer

I would rather use UISegmentedControl when switching between three states.

Create an IBAction with CTRL dragged connection from your Storyboard's UISegmentedControl element.

Implement the method as following:

@IBAction func segmentedControlChanged(_ sender: UISegmentedControl) {

    print(sender.selectedSegmentIndex)        
    // if states within your control is indexed in following order: Standard, Satellite, Hybrid:

    switch sender.selectedSegmentIndex {
        case 0:
            Mapview.mapType = MKMapType.Standard
        case 1:
            Mapview.mapType = MKMapType.Satellite
        case 2:
            Mapview.mapType = MKMapType.Hybrid
        default:
            Mapview.mapType = MKMapType.Standard
    }            
}