iosswiftuipickerviewuipickerviewdatasource

Setting UITextField's inputView property to a UIPicker not working in Swift


Hello I am trying to pop a UIPickerView view programmatically when user clicks on textfield. I have tried this but it doesn't doing anything, it isn't working. Nothing is happening when I click the textfield

class UserProfileTableViewController: UITableViewController,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource {
 var itemPicker: UIPickerView! = UIPickerView()
    
    @IBOutlet weak var genderTxtField: UITextField!
   
    
    var gender = ["MALE","FEMALE"]
    override func viewDidLoad() {
        super.viewDidLoad()
       
        genderTxtField.delegate = self
        
        itemPicker!.delegate = self
        itemPicker!.dataSource = self
        itemPicker!.backgroundColor = UIColor.blackColor()
    
        self.genderTxtField.inputView = itemPicker
    }
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
        return 1
    }
    
    // returns the # of rows in each component..
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        return gender.count
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return gender[row]
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        genderTxtField.text = gender[row]
        //.hidden = true;
    }
    
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        itemPicker.hidden = false
        return false
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Solution

  • The issue in your current code is in this method:

    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        itemPicker.hidden = false 
        return false // <--- this is not letting the textField become editable
    }
    

    I would suggest removing this method entirely.