Show a UIPickerView for a UITextField
Sometimes for a UITextField we want to show the user a set of options. However, we don’t want to show the keyboard or the cursor in the box. So how can we achieve all of this? I did it as per below:
1. Download the ActionSheetPicker project from the following link: https://github.com/TimCinel/ActionSheetPicker
2. Implement the UITextFieldDelegate in the class you are working in, and make sure the delegate has been set for the particular UITextField.
3.Provide the following code in the class implementing UITextFieldDelegate:
// Delegate function - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { // We are now showing the UIPickerViewer instead // Close the keypad if it is showing [self.superview endEditing:YES]; // Show the UIPickerView instead [self showPickerViewer :array :pickerTitle]; // Return NO so that there won't be a cursor in the box return NO; } // Show the UIPickerView - (void)showPickerViewer:(NSArray *)items :(NSString *)title { ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) { if ([txtFields respondsToSelector:@selector(setText:)]) { [txtFields performSelector:@selector(setText:) withObject:selectedValue]; } selectedRow = selectedIndex; }; ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) { NSLog(@"UIPicker was cancelled."); }; [ActionSheetStringPicker showPickerWithTitle:title rows:items initialSelection:selectedRow doneBlock:done cancelBlock:cancel origin:txtFields]; }
The above code will close the keyboard, show the UIPickerView, and return NO for editing (this will eliminate the cursor from the view.
And we’re done!