2010-06-02 53 views
2

我有多个可编辑文本文件,其中一些文本覆盖了键盘。所以我使用UIScrollView,它工作得很好。使用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方法......但当键盘被隐藏时,它们会导致故障。

回答

0

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

+0

你是什么意思?我正在检查键盘是否显示/隐藏不止一次。但在键盘可见时,如果用户点击不同的文本字段,它将触发隐藏事件,然后是隐藏事件...在隐藏事件期间,我无法确定是否会出现显示事件。这就是问题 – Antriel 2010-06-02 18:23:27

+0

在'keyboardDidShow'上设置了布尔值1,在'keyboardDidHide'上设置为0 - 这些只在键盘在事件发生前不可见时触发。 – jrtc27 2010-06-02 19:11:28

+0

问题是即使用户触摸不同的文本字段时,keyboardDidHide也会被触发。但键盘不会隐藏,它只会触发隐藏事件和显示事件。 – Antriel 2010-06-02 19:31:13

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