Dyna Dyna - 4 months ago 13
Objective-C Question

Close text field when a number of characters is inserted

I have a text field where I want to insert a phone number. The problem is that I use number pad and there is not any enter key and I without that key I don't know how to close the text field.

Is there any way of checking how many number os characters there are in a text field and close the number pad when there are X chars?

Sorry for my english and sorry for the noob question but I am just starting with ObjC.

Thanks *

Sorry guys, I forgot to tell you that I already have tried this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

if (textField.text.length== 9) {
[textField resignFirstResponder];

}
return YES;
}

Answer

Yes, you have two choices in my opinion, you can:

A. Check the number of chars returned in delegate method shouldChangeTextInRange and then if your limit is reached resign first responder (when you resign first responder the keyboard dismisses,

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ( textView.text.length + (text.length - range.length) == 10) //or whatever value you like
    {
        [textField resignFirstResponder];
    } 
}

Or B:

Override the touchesEnded method of your view and call resignFirstResponder, so that when the user touches the view outside the textField, the keyboard dismisses. - this is what I do in my app.

Like this:

Just add this method to your viewController, it will be called automatically when the touch in the view ends, in this method you simply resignFirstResponder and the keyboard will disappear.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [textField resignFirstResponder];
}

I think it's better to do this in touchesEnded than began, it 'feels' nicer to have the keyboard dismiss when you lift your finger from the view, rather than when to initially touch it.