I have 8 textfields in one view. I want to populate each using a pickerview.
Can I have 1 pickerview which will display different list of items from different arrays for different textfields?
Can someone explain how do I do it programmatically with a sample code?
Also how can I hide the pickerview when the view loads and it should be displayed only when I click on a textfield with its corresponding data list? It should disappear when I select the data and reappear when I click on a different textfield with its corresponding data list and so on.
I am new to xcode. Any help will be much appreciated. Thank you.
You can use only one PickerView that shows different data depending on some conditions.
My idea is the following: you could create, lets say, 8 different arrays – one for populating the UIPickerView depending on what UITextField was tapped. Declare them in the interface as NSArray and initialize in viewDidLoad:
Then you create another just to point the array that should fill it (like
NSArray *currentArray) and you don’t even need to init it = it will be used only for pointing the correct array.So you should set the delegate of the UITextFields to your view controller, and in the method
textFieldShouldBeginEditingyou check who is the UITextField, assign the correct array as the currentArray, reload the UIPickerView withreloadData, and return NO in the sametextFieldShouldBeginEditingmethod. currentTextField is a pointer only to know what is the currentUITextField being “edited” – we need to store it to be able to set the text after selecting data in the picker. Declare currentTextField in the interface.So, when your view controller, that in fact is the UIPickerViewDelegate, you populate your UIPickerView according to the current array and you don’t need to change anything, just use the currentArray as the array to get data from.
Now, to show the pickerView:
After connecting the IBOutlet, in your viewDidLoad you should do two things: set the frame of the UIPickerView and add it as a subview:
Now you need to create the method called
animatePickerViewIn, that we called when the user taps the UITextField.To load the data in the pickerView:
And when the user selects the row in the pickerView, you will receive it as a delegate method. So just set the text of the currentTextField as the value selected: