[Solved] Swift – how to read data from many UITextFields which generate data by UIPickerView [closed]


You can set a pickerView as the textField.inputView.

The example below is for two text fields sharing a single picker view, but you can extend it easily by checking the identity of the activeTextField in the picker view delegate methods.

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var myTextFieldOne: UITextField!
    @IBOutlet weak var myTextFieldTwo: UITextField!

    let pickerDataOne = ["A", "B", "C", "D", "E", "F"]
    let pickerDataTwo = ["1", "2", "3", "4", "5", "6"]

    // Holds a reference to current text field
    var activeTextField = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        let myPicker = UIPickerView()
        myPicker.delegate = self
        myPicker.dataSource = self
        myTextFieldOne.inputView = myPicker
        myTextFieldTwo.inputView = myPicker
    }

    // MARK: UITextField Delegate

    func textFieldDidBeginEditing(textField: UITextField!) {
        // Sets tapped textField to active one
        self.activeTextField = textField
        if let picker = self.activeTextField.inputView as? UIPickerView {
            // This is one way to get a reference to the picker view
            picker.reloadAllComponents()
        }
    }

    // MARK: UIPickerView Delegate

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

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        // You can have a different data source for each text field
        if activeTextField === myTextFieldOne {
            return pickerDataOne.count
        } else if activeTextField === myTextFieldTwo {
            return pickerDataTwo.count
        }
    }

    func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        // Gets the title for each row in picker
        if activeTextField === myTextFieldOne {
            return pickerDataOne[row]
        } else if activeTextField === myTextFieldTwo {
            return pickerDataTwo[row]
        }
    }

    func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        // Populates the text field
        if activeTextField === myTextFieldOne {
           myTextFieldOne.text = pickerDataOne[row]
        } else if activeTextField === myTextFieldTwo {
           myTextFieldTwo.text = pickerDataTwo[row]
        }
    }

}

You can then access the text in any text field by getting myTextFieldOne.text for example.

6

solved Swift – how to read data from many UITextFields which generate data by UIPickerView [closed]