0

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
    }
}
0-1
  • 702
  • 1
  • 10
  • 30

1 Answers1

0

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")
 }
Mahendra
  • 8,448
  • 3
  • 33
  • 56
  • that is already happening, all I want before submitting the picker value to verify that the value is from the array already set for that, how to do that with the guard statement? – ramneek kashyap Nov 21 '19 at 12:59
  • If input view is a picker view (not keyboard), it means the value must selected form keyboard. SO I think you no need to check that one. – Mahendra Nov 21 '19 at 13:24