Programmatically create and show UIPickerView

I am trying to create a UIPickerView programmatically and display it as the firstResponder of a text field, however the selection view does not appear. textField connects to the object in the interface builder, but pickerView is created programmatically.

class View: UIViewController { @IBOutlet var picker : UIPickerView = UIPickerView.alloc() @IBOutlet var textField : UITextField = nil override func viewDidLoad() { super.viewDidLoad() picker = UIPickerView() picker.delegate = self picker.dataSource = self picker.backgroundColor = UIColor.blackColor() textField.inputView = picker } } extension View: UIPickerViewDataSource { func numberOfComponentsInPickerView(colorPicker: UIPickerView!) -> Int { return 1 } func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int { return 5 } } extension View: UIPickerViewDelegate { func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! { return "Text" } } 

Why can't I see this pickerView when the application starts?

Edit: adding a breakpoint inside the extensions does not stop the program; they are not called.

+6
source share
3 answers

I found a problem - the code for assigning the input view does not include self. He must read

 self.textField.inputView = picker 
+4
source

I am not sure why you do not see the collector. But this is the wrong way.

To create an instance using:

  picker = UIPickerView.alloc() 

In Swift:

you should use:

 picker = UIPickerView() 
+2
source

I had the same problem trying to display a picker view when clicked in a text box. My problem was that for some reason, my iOS simulator checked the “Connect Hardware Keyboard”. In the iOS menu, open Hardware → Keyboard and make sure that “Connect Hardware Keyboard” is not installed. He feels dumb without noticing that some kind of keyboard appeared in the application for several hours, but I hope this helps save someone else from disappointment.

I just wanted to add editing: in the iOS simulator, you can try switching to the soft keyboard (command + K). In this case, it worked for me, and allowed me to connect a hardware keyboard. Just check something quickly before you consider the code incorrect.

+2
source

Source: https://habr.com/ru/post/972482/


All Articles