Keyboard handling with UITextField in iPhone or iPad

Today we are going for keyboard handling with UITextField. In order to handle keyboard, first of all we have to set and implement UITextField delegate. In our scenario we are going to add 5 UITextfields in view and assign them tags zero to five.

If user enters in other than first 3 text fields then we will slide our view up side and the text fields on the bottom will come visible.

So here we go with UITextField delegate Methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
 
	[textField resignFirstResponder];
	return YES;
}
 
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}
 
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}
 
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    if (textField.tag==3||textField.tag==4) {
        const int movementDistance = 120; // tweak as needed
        const float movementDuration = 0.3f; // tweak as needed
 
        int movement = (up ? -movementDistance : movementDistance);
 
        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.view.frame, 0, movement);
        [UIView commitAnimations];
 
    }else if (textField.tag==5){
        const int movementDistance = 150; // tweak as needed
        const float movementDuration = 0.3f; // tweak as needed
 
        int movement = (up ? -movementDistance : movementDistance);
 
        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.view.frame, 0, movement);
        [UIView commitAnimations];
 
    }
}

You may change value of ‘movementDistance’ and ‘movementDuration’ according your needs. Sample project is available TextFieldUpProject
Happy coding and Mind Your Code :)

About Qasim Masud

Leave a Reply