用UIScrollView隐藏键盘,没有毛刺

时间:2010-06-02 17:28:10

标签: iphone objective-c keyboard uiscrollview

我有多个可编辑的textfiels,其中一些用键盘覆盖。所以我使用了UIScrollView,效果很好。

问题是当我想要隐藏键盘时。如果我向下滚动,键盘隐藏后,一切都会在开始时跳起来(没有键盘)。当键盘隐藏时,我想补间这部分 到目前为止,我得到了这个代码(键盘事件的2种方法):

-(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];
}

隐藏键盘效果很好,但不幸的是,当用户从一个文本字段切换到另一个文本字段时,它不起作用。它将触发keyboardWillHide和keyboardWillShow事件,一个接一个。这将导致两个动画,第二个动画中断第一个动画。它看起来不太好。

问题在于即使键盘无法隐藏,也会触发keyboardWillHide。那时我不知道键盘是否会再次显示。

我还尝试使用UIScrollView scrollRectToVisible和setContentOffset方法..但是当键盘隐藏时它们会导致毛刺。

2 个答案:

答案 0 :(得分:3)

使用此方法处理多个文本字段和键盘

-(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;
}

答案 1 :(得分:0)

为什么不使用布尔值来表明它是外观还是只是改变?