Search code examples
iosswiftstoryboarduitextfielduipickerview

Can't set programmatically created UITextField text to UIPickerView value


I've created a UITextField programmatically (myTextField : UITextField!) so I can easily control its attributes.

I want to be able to set its text to the selected value of a UIPicker (programmatically created via myPickerView: UIPickerView! = UIPickerView()), but whenever I try myTextField.text = pickerData[row] inside didSelectRowthe app crashes saying nil was found while unwrapping an Optional.

I'm using myTextField.inputView = myPickerView which behaves properly and I can successfully print out the selected row from the picker view. It's only when I try to set the text that it crashes.

When I set up a button on the storyboard as an IBOutlet it works properly, but I want to avoid using storyboard. Is there anyway around this? Or is it possible to style a storyboard button programmatically?

UPDATE: I've set a tag to myTextField and set myTextField.text using the tag under the pickers didSelect protocol, but that feels roundabout and hacky


Solution

  • Your textfield is nil. You need to initialize the textField before using the pickerView. Best method is

    myTextField = UITextField()
    myTextField.inputView = myPickerView
    

    So that, the pickerView appears only when you touch the textField. If you want it to be open by default, use

    myTextField.becomeFirstResponder()