Search code examples
iosswiftconsoleuipickerview

Print to the console what is currently selected with my uipickerview?


Here is the code that I have:

class WelcomeViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    @IBOutlet weak var locationPicker: UIPickerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationPicker.delegate = self
        locationPicker.dataSource = self
    }

    var locationData = ["San Fransisco", "New York", "London", "Paris", "Rio", "Bejing"]

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return locationData.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return locationData[row]
    }
}

I would like to print to the console the location that is currently selected so each location can send the user to a different screen.


Solution

  • You need the didSelectRow method of UIPickerViewDelegate.

    func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
        {
            let location = locationData[row]
            print(location)
    
        }