2010-06-02 49 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; 
}