Today's code snipett tries to help the developer to avoid this issue. What we shall do is to move the UIView up when keyboard shows and move it down again when keyboards hides. To accomplish that we have tu use observers, and implement the two methods that will be called when keyboards shows and hides.
First, we have to add the observers to NSNotificationCenter default center for the events of showing and hiding the keyboard Implements this in viewDidLoad method.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];After that we implement both methods. We have to calculate the height at our hidden UITextField is, for adding or substract it from view's frame origin in order to move the UIView up and down. If we have more than one UITextField controls we shall to detect which is the first responder and sets the position accord to it.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
- (void) keyboardWillShow: (NSNotification*) aNotification;And with this code snippet you will have a professional application that provides a good user experience and an animated interface when editing.
{
int position = 0;
if ([textField1 isFirstResponder])
position = 100;
else if ([textField2 isFirstResponder])
position = 150;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
CGRect rect = [[self view] frame];
rect.origin.y -= position;
[[self view] setFrame: rect];
[UIView commitAnimations];
}
- (void) keyboardWillHide: (NSNotification*) aNotification;
{
int position = 0;
if ([textField1 isFirstResponder])
position = 100;
else if ([textField2 isFirstResponder])
position = 150;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
CGRect rect = [[self view] frame];
rect.origin.y += position;
[[self view] setFrame: rect];
[UIView commitAnimations];
}
Enjoy it!
No comments:
Post a Comment