Search code examples
swiftuikituipickerview

How do you use a UIPickerView to determine the value of a UITextField?


I've built a UIPickerView that lets the user pick from all of the states in the US. My goal is for the user to tap on the UITextField and for the UIPickerView to pop up with the options. How do I join the UITextField and the UIPickerView?

Thanks!


Solution

  •     // define variables 
        var timeSlotsPickerView = UIPickerView()
        @IBOutlet weak var timeSlotTextField: BasicTextField!
    
    
         override func viewDidLoad() {
                super.viewDidLoad()
                timeSlotsPickerView.delegate = self
                timeSlotTextField.inputView = timeSlotsPickerView // textfield inputview will open pickerview
            }
    
    use the delegate and datasource methods of pickerview
    
     func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int {
            return array.count
        }
    
        func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return array[row]
        }
    
        func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            timeSlotTextField.text = "\(array[row])"
        }