Search code examples
iosswiftuitextfielduipicker

how to ensure only picker data is selected in the textfield


I am using following code for the picker function in a UITextfield, how should I ensure that the value from the array is chosen and no other data input is there I shared the code below, I used the "guard" to check whether field is empty or not Code

var spinneCPickerData: [String] = ["1", "2", "3", "4", "5"]
@IBOutlet var pickerfield: UITextField!
    
override func viewDidLoad() {
    super.viewDidLoad()
            
    let spinnerCPicker = UIPickerView()
    spinnerCPicker.delegate = self
    pickerfield = spinnerCPicker
}
    
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
        
func pickerView( _ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {      
    return spinneCPickerData.count
}
        
func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return spinneCPickerData[row]
}
        
func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    pickerfield.text = spinneCPickerData[row] as String
    view.endEditing(true)
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
}
    
func setdata() {
    guard let text data = PostCategoryField.text, !postcategory.isEmpty,  else {
        self.view.makeToast("Please Enter the Category!")
        return
    }
}

Solution

  • You need to set inputView to your pickerfield.

    Like this way you can do...

    Declare a property pickerView

     private let pickerView = UIPickerView(frame: .init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 216))
    

    The in viewDidLoad method set the delegate and datasource.

        pickerView.dataSource = self
        pickerView.delegate = self
        pickerfield.inputView = pickerView
    

    So when pickerfield become first responder then picker view will be displayed in place of keyboard.

    So user has to select a value from picker view

    UPDATE

    You can do this by if-let in following way. You need to put this code where you want to validate the value of textfield.

    //When pickerfield.text value is one of the value of spinneCPickerData array
    if let txt = pickerfield.text, spinneCPickerData.contains(txt) {
    
           print("the textfield'd value is from the array")
     }