One short question: on a registration process I would like to ask the user to choose a value from a list of values.
Is it the right way to use a view Controller adding there all text fields and for the values a picker view? As the picker view needs so much space in between the text fields area I wonder what the best practice in this case would be?
this is my code so far:
class RegisterViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{
@IBOutlet weak var gradeTextField: UITextField!
@IBOutlet weak var gradePicker: UIPickerView!
let gradePickerValues = ["5. Klasse", "6. Klasse", "7. Klasse"]
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return gradePickerValues.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return gradePickerValues[row]
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
gradeTextField.text = gradePickerValues[row]
self.view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
statusMessageLabel.hidden = true
gradePicker.dataSource = self
gradePicker.delegate = self
gradePicker.hidden = true
gradeTextField.inputView = UIPickerView()
gradeTextField.text = gradePickerValues[0]
}
The pickerview is hidden at the beginning and appears only when I select the text field, this is fine so far... But the the picker view is empty...
First set delegate
set IBOutlet for UIPickerView
Take an array for data
Write this code on viewDidLoad()
Write picker view delegate methods:
100% working and tested
It depends on controller appearance. If there only one choose action per screen it will be better to put
Table View
on it and selected row will be current selection.If screen has multiply fields, that user should act with, then, in my opinion, it's better to put
label
+button
above it and when user press thisbutton
you just showsPicker View
from screen bottom. When user select any row inPicker View
you change label text, but don't hide picker itself, it should be done by pressing "Done"button
you place above.Hope this helps.
Update:
Your problem because you just forget to set
dataSource
property ofUIPickerView
Just do:
gradePicker.dataSource = self
inviewDidLoad()
And don't forget to implements protocol here:
class RegisterViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource
Update 2:
Finally made it. If you add
UIPickerView
in inputView of your textFiled, then It should NOT be in IB. So you could remove it from storyboard (or .xib, if you use it).Then change code to be something like this: