In my app I have a text field that takes some number input from user so i set the keyboard type to "Number Pad"but now i am stuck as to how should i dismiss it when user finishes giving input . i know i have to use the delegate method "textfieldShouldReturn" but the problem is that number pad dont have a return key.so is it necessary to add a custom done key on the keyboard or there is some other way out?
Another solution - Add inputAccessoryView
to yourNumberTextFiled
- (void)viewDidLoad
{
[super viewDidLoad];
UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
numberToolbar.barStyle = UIBarStyleBlackTranslucent;
numberToolbar.items = [NSArray arrayWithObjects:
[[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)],
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
[[UIBarButtonItem alloc]initWithTitle:@"Apply" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)],
nil];
[numberToolbar sizeToFit];
numberTextField.inputAccessoryView = numberToolbar;
}
-(void)cancelNumberPad{
[numberTextField resignFirstResponder];
numberTextField.text = @"";
}
-(void)doneWithNumberPad{
NSString *numberFromTheKeyboard = numberTextField.text;
[numberTextField resignFirstResponder];
}
You need to add a background tap
-(IBAction)backGroundTap:(id)sender
in the dot h and then in the dot m file
-(IBAction)backGroundTap:(id)sender
[nameField resignFirstResponder];
[numberField resignFirstResponder];
If you know the length of the number to be entered (e.g. a 4-digit PIN) you could auto-dismiss the keypad after 4 keys entered.
I hit a problem resigning the first responder after 4 keys (it would ignore the last keypress if you returned YES after resigning, so I added an async delay to the resign.
This code is in the UITextField delegate:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// max 4 keypresses
if(range.location == 3){
// async workaround for can't return YES after resignFirstResponder
[self performSelector:@selector(closeKeypad:)
withObject:textField
afterDelay:0.1
];
}
else if(range.location > 3){
return NO;
}
return YES;
}
-(void) closeKeypad:(UITextField*)textField {
[textField resignFirstResponder];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With