Imitate UIPickerView behavior on safari

10:44 PM 0 Comments

When the user encounter a drop-down box while browsing the web the safari loads a UIPicker view in order to populate the selections and present it to the user.
On one of my resent projects I needed this same functionality but implemented as a native solution and not as web-view/html solution.
The solution I found was using the UIActionSheet control that contains a UIPickerView as a subview.

In the .h file include:

UIActionSheet * pickerContainer;
UIPickerView * pickerItems;

In the .m file include this code on the viewDidLoad method:

pickerContainer = [[UIActionSheet alloc] init];
pickerItems = [[UIPickerView alloc] initWithFrame:CGRectMake(0,0,0,0)];
pickerItems.delegate = self;
[pickerContainer addSubview:pickerItems];

And when you want the picker to appear on screen execute this code:

[pickerContainer showInView:self.view];
[pickerContainer setBounds:CGRectMake(0,0,320,400)];

This will make the ActionSheet appear on screen in the same way the picker appears when you select a drop-down element on an HTML page.
You can also add buttons above the UIPickerView in order to mimic the same functionality that happens on web views.

Happy coding!

Netanel Lev

0 comments: