Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS how to implement a drop down list and how to take care of closing it?

I need some inputs on how to implement dropdown list kind of functionality in iOS.

I have some solutions in mind like using UITableView for displaying the list of text items. (in my case the list could be static as well as dynamic so UITableView seems to be a good option for my case). But one thing I am not able to figure out is how to dismiss the dropdown...

Let's say there is this dropdown list open somewhere in a view (let's say this view occupies the complete screen). The dropdown, once opened, should get dismissed (closed) when I tap somewhere else in the view, like the way a typical dropdown works in desktop environment. How do I do that?

One way is to listen to touchesBegan events on the view and see if the dropdown is open -this is fine but problem is if I have things like button and when user clicks on one of them then I don't receive the touchesBegan input on the view.

How do I go about solving this in a generic way?

like image 382
naiveCoder Avatar asked Mar 12 '12 17:03

naiveCoder


1 Answers

Drop down lists are usually implemented in iOS using a UIPickerView. The picker view can be set as the input view of the text field which would hold the drop down, it is then animated on and off screen in the same manner as the keyboard.

You usually also need a UIToolbar holding a "Done" button as the input accessory view, this appears above the picker and allows you to dismiss once a choice is made if you're not doing that automatically.

You remove the picker by sending resignFirstResponder to the text field, either from a picker view delegate method or the action method of your done button.

You create the toolbar as an accessory view as follows:

accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
accessoryView.barStyle = UIBarStyleBlackTranslucent;

UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTapped:)];

accessoryView.items = [NSArray arrayWithObjects:space,done, nil];

textField.inputAccessoryView = accessoryView;

This will give you a single "Done" button on the right which is connected to an action method called doneTapped:

like image 177
jrturton Avatar answered Sep 28 '22 01:09

jrturton