Code to show UIPickerview under clicked UITextField
- by Chris F
I thought I'd share a code snippet where I show a UIPickerView when you click a UITextField. The code uses a UIPickerView, but there's no reason to use a different view controller, like a UITableViewController that uses a table instead of a picker.
Just create a single-view project with a nib, and add a UITextField to the view and make you connections in IB.
// .h file
#import
@interface MyPickerViewViewController : UIViewController <UIPickerViewDelegate,
UIPickerViewDataSource,
UITextFieldDelegate>
- (IBAction)dismissPickerView:(id)sender;
@end
// .m file
#import "MyPickerViewViewController.h"
@interface MyPickerViewViewController () {
UIPickerView *_pv;
NSArray *_array;
IBOutlet __weak UITextField *_tf;
BOOL _pickerViewShown;
}
@end
@implementation MyPickerViewViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_pickerViewShown = NO;
_array = [NSArray arrayWithObjects:@"One", @"Two", @"Three", @"Four", nil];
_pv = [[UIPickerView alloc] initWithFrame:CGRectZero];
_pv.showsSelectionIndicator = YES;
_pv.dataSource = self;
_pv.delegate = self;
_tf.delegate = self;
_tf.inputView = _pv;
}
- (IBAction)dismissPickerView:(id)sender
{
[_pv removeFromSuperview];
[_tf.inputView removeFromSuperview];
[_tf resignFirstResponder];
_pickerViewShown = NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (!_pickerViewShown) {
[self setRectForPickerViewRelativeToTextField:textField];
[self.view addSubview:_tf.inputView];
_pickerViewShown = YES;
}
else {
[self dismissPickerView:self];
}
return NO;
}
- (void)setRectForPickerViewRelativeToTextField:(UITextField*)textField
{
CGFloat xPos = textField.frame.origin.x;
CGFloat yPos = textField.frame.origin.y;
CGFloat width = textField.frame.size.width;
CGFloat height = textField.frame.size.height;
CGFloat pvHeight = _pv.frame.size.height;
CGRect pvRect = CGRectMake(xPos, yPos+height, width, pvHeight);
_pv.frame = pvRect;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [_array objectAtIndex:row];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return _array.count;
}
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
_tf.text = [_array objectAtIndex:row];
[self dismissPickerView:self];
}
@end