Search code examples
iphoneiosxcodeuitextfielduipickerview

How to use UIPickerView to populate different textfields in one view?


I have a view with 8 textfields. I want each textfield to be associated with a pickerview which will have different items. This pickerview should populate each text field.

When I click on the textfield it should show the pickerview and the items associated with it and when I select the item for that textfield it should dismiss the pickerview. Then again when I click on next textfield it should show the pickerview with the items for that text field and so on...

Is it possible to do so? I am new to xcode. Any help is much appreciated. Thank you.


Solution

  • Absolutely possible. Here's my best recommendation:

    1. Create 8 arrays--one for each picker view. Within these arrays, contain the options that the user should be able to choose from. This can be easily accomplished with NSArray.
    2. Set up your textfields in Interface Builder (i.e. in your Storyboard file), and connect an IBAction from each textfield to a function within the view controller's code.
    3. Within each of these functions, instantiate a new UIPickerView with the contents of the array corresponding to the current picker.
    4. After the user has selected the item, set the textfield's content to the array value contained within the index selected by the picker.
    5. Remove the picker from the current view.

    As I here you're new to Xcode, let me know if you need any additional explanation.

    BTW, here is the class reference for UIPickerView: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIPickerView_Class/Reference/UIPickerView.html

    UPDATE: In the function that is triggered when the textfield is tapped, allocate and instantiate the picker. Then, add it to your view. Afterwards, simply remove it from the view when the user has finalized his selection.