Programmatic Controls has wrong

#1

Hello everyone :blush:

iOS Programming is pretty new to me, what’s wrong with it ? please help me ! Thank you !

import UIKit
import MapKit

class MapViewController: UIViewController {

var mapView: MKMapView!

override func loadView() {
    mapView = MKMapView()
    view = mapView
    
    let segmentedControl = UISegmentedControl(items:["Standard","Hybrid","Satellite"])
    segmentedControl.backgroundColor = UIColor.white
    segmentedControl.selectedSegmentIndex = 0
    
    segmentedControl.addTarget(self, action: "mapTypeChanged:", for: .valueChanged)  // ERROR HERE
    
    segmentedControl.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(segmentedControl)
    
    let topConstraint = segmentedControl.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 8)
    
    let margins = view.layoutMarginsGuide
    let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
    let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
    
    topConstraint.isActive = true
    leadingConstraint.isActive = true
    trailingConstraint.isActive = true
    
    func mapTypeChanged(segControl: UISegmentedControl) {
        switch segControl.selectedSegmentIndex {
        case 0:
            mapView.mapType = .standard
        case 1:
            mapView.mapType = .hybrid
        case 2:
            mapView.mapType = .satellite
        default:
            break
        }
    }
}

segmentedControl.addTarget(self, action: “mapTypeChanged:”, for: .valueChanged) // ERROR HERE

The “ERROR HERE” line has a warning :
No method declared with Objective-C selector ‘mapTypeChanged:’

#2

Do you have the function mapTypeChanged: defined nested inside the function loadView? If that’s the case, it is a problem, and you need to move that function out of loadView; it needs to be at the same level as loadView.

Also action: “mapTypeChanged:” needs to be action: #selector (mapTypeChanged:)

#3

You are so helpful :laughing:

  1. I move the function mapTypeChanged out of loadView

  2. I change the code

         segmentedControl.addTarget(self, action: #selector(MapViewController.mapTypeChanged(segControl:)), for: .valueChanged)
    

Then it works.

Forgive me for my poor English and really appreciate your help.