Hiding keyboard with UIScrollView without glitches
I have multiple editable textfiels and some of them are covered with keyboard. So I used UIScrollView and it works quite nice.
Problem is when I want to hide keyboard. If I was scrolled down, after the keyboard hides, everything jumps up as it was at beginning (without keyboard). I want to tween this part as the keyboard is hiding.
So far I got this code (2 methods for keyboard events):-(void)keyboardWillShow:(NSNotification *)notif{
if(keyboardVisible)
return;
keyboardVisible = YES;
NSDictionary* info = [notif userInfo];
NSValue* value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
CGRect viewFrame = self.view.frame;
viewFrame.size.height -= keyboardSize.height;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3];
[scrollView setFrame:viewFrame];
[UIView commitAnimations];
}
- (void)keyboardWillHide:(NSNotification *)notif{
if(!keyboardVisible)
return;
keyboardVisible = NO;
NSDictionary* info = [notif userInfo];
NSValue* value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
CGRect viewFrame = self.view.frame;
viewFrame.size.height += keyboardSize.height;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3];
[scrollView setFrame:viewFrame];
[UIView commitAnimations];
}
It works pretty well with hiding keyboard but unfo开发者_如何转开发rtunately it doesn't work when user switches from one text field to another. It will fire keyboardWillHide and keyboardWillShow events, one right after another. This will result in two animations, second one interrupting the first one. It doesn't look good.
Problem is with keyboardWillHide firing even when keyboard will not hide. At that point I don't know if keyboard will be shown again or not.
I also tried it with UIScrollView scrollRectToVisible and setContentOffset methods.. but they resulted in glitches when keyboard was hiding.
use this method to handle multiple text field and keyboard
-(void)scrollViewToCenterOfScreen:(UIView *)theView
{
CGFloat viewCenterY = theView.center.y;
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
CGFloat availableHeight = applicationFrame.size.height - 200; // Remove area covered by keyboard
CGFloat y = viewCenterY - availableHeight / 2.0;
if (y < 0) {
y = 0;
}
[scrollview setContentOffset:CGPointMake(0, y) animated:YES];
}
call it in textfield delegate=
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self scrollViewToCenterOfScreen:textField];
}
and set scroll view frame in the below textfield delegate=
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
[self.scrollview setContentOffset:CGPointMake(0, 0) animated:YES];
return YES;
}
Why not use boolean values to indicate whether it is an appearance or just changing?
精彩评论