swiftuipickerviewuipickerviewdatasourceuipickerviewdelegate

How can i reach of selected item's title and item's value in picker in swift?


Let me describe view controller (page design) side first. I added one picker view, one label and one button, here is my viewController file

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    //var myArray2 = [["Alex", "de Souza", "1977"],["Ariel", "Ortega", "1974"],["Lefter", "KucukAndonyadis", "1925"]]
    //structure of myArray2: name, lastname, bday

    var myArray = ["Alex", "de Souza", "1977"]

    var indexValueOfSelectedItem = 0
    var nameValueOfSelectedItem = ""
    var lastnameValueOfSelectedItem = ""
    var bdateOfSelectedItem = 0

    @IBOutlet weak var lblResult: UILabel!
    @IBOutlet weak var pickerStudent: UIPickerView!
    override func viewDidLoad() {
        super.viewDidLoad()
        pickerStudent.delegate = self
        pickerStudent.dataSource = self
    }

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

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

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

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        indexValueOfSelectedItem = row
        //nameValueOfSelectedItem = row
        //lastnameValueOfSelectedItem = row
        //bdateOfSelectedItem = row
    }

    @IBAction func buttonClick(_ sender: Any) {
        lblResult.text = String (indexValueOfSelectedItem)
    }
}

If i use myArray2 instead of myArray, how can i reach name of selected item details, like name, last name etc ? I would like to show name, lastname and bday of selected item in label.


Solution

  • func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return myArray2[row][0]
        }
    
        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return myArray2.count
        }
    
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }
    
        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            indexValueOfSelectedItem = row
    
            print("name: \(myArray2[indexValueOfSelectedItem][0])")
            print("last name: \(myArray2[indexValueOfSelectedItem][1])")
            print("birthdate: \(myArray2[indexValueOfSelectedItem][2])")
        }