iosiphoneswiftuipickerviewuipicker

Can my UIPickerview output be different that the input?


I have a picker view that will eventually have 4 values. Is there a way to keep the items in the picker view, but have it output a different value to the label? Like can the picker view display "4" but output to the label "8" for example?

Heres my code so far:

import UIKit

class GCSViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {

@IBOutlet var eyepicker: UIPickerView!
@IBOutlet var eyeoutput: UILabel!
let pickerData = ["1","2","3","4"]
override func viewDidLoad() {
    super.viewDidLoad()
    eyepicker.dataSource = self
    eyepicker.delegate = self
}

//mark: - Delegates and data sources
//MARK: Data Sources

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
}
//MARK: Delegates
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    eyeoutput.text = pickerData[row]
}
//The first method places the data into the picker and the second selects and display
}

Solution

  • option 1:

    let pickerData = ["1","2","3","4"]
    let outputData = ["2","4","6","8"]
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
      eyeoutput.text = outputData[row]
    }
    

    option 2 (with a guessed algorithm):

    let pickerData = ["1","2","3","4"]
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
      eyeoutput.text = "\(Int(pickerData[row])! * 2)"
    }