[英]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. 我已经以编程方式创建了一个
UITextField
( myTextField : UITextField!
),因此我可以轻松地控制其属性。
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. 我希望能够将其文本设置为UIPicker的选定值(通过
myPickerView: UIPickerView! = UIPickerView()
编程创建myPickerView: UIPickerView! = UIPickerView()
),但是每当我在didSelectRow
尝试myTextField.text = pickerData[row]
,应用程序都会崩溃,提示nil为展开Optional时找到。
I'm using myTextField.inputView = myPickerView
which behaves properly and I can successfully print out the selected row from the picker view. 我使用的
myTextField.inputView = myPickerView
行为正常,我可以从选择器视图中成功打印出选定的行。 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. 当我在情节提要板上将按钮设置为IBOutlet时,它可以正常工作,但我想避免使用情节提要。 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 更新:我已经将标签设置为
myTextField
并使用了didSelect
协议下的标签设置了myTextField.text
,但是感觉有点round回
Your textfield is nil. 您的文本字段为nil。 You need to initialize the textField before using the pickerView.
您需要在使用pickerView之前初始化textField。 Best method is
最好的方法是
myTextField = UITextField()
myTextField.inputView = myPickerView
So that, the pickerView appears only when you touch the textField. 因此,pickerView仅在您触摸textField时出现。 If you want it to be open by default, use
如果您希望默认情况下将其打开,请使用
myTextField.becomeFirstResponder()
我认为您在设置文本之前没有初始化文本字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.