简体   繁体   中英

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 didSelectRow the 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

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()

我认为您在设置文本之前没有初始化文本字段。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM