2014-12-04 42 views
0

我有一個視圖,其頂部有一個tableview和一個搜索文本框(帶按鈕)在tableview底部。我正在嘗試實現動態搜索,以便在用戶鍵入tableview時重新加載。搜索字段在鍵盤上很好地進行搜索。但在某些情況下,當用戶仍然在打字時,它會在鍵盤下方。這通常發生在搜索返回0結果時,這意味着tableview爲空,或者如果tableview具有適合分配給tableview的高度的行。我不知道爲什麼tableview重新加載會使搜索字段回到頁面的底部,即使搜索字段不是tableview的一部分。問題與搜索文本框和表格視圖

這裏是我使用基於鍵盤狀態來移動搜索字段中的代碼:

- (void)adjustView:(NSNotification *)notification { 
    CGRect keyboardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; 
    keyboardFrame = [self.view convertRect:keyboardFrame fromView:self.view.window];  
    CGRect viewFrame = self.searchView.frame; 
    viewFrame.origin.y = keyboardFrame.origin.y - viewFrame.size.height; 
    self.searchView.frame = viewFrame; 

} 

這裏搜索查看是包含文本字段和一個按鈕的圖。 任何幫助,不勝感激。

+0

textfield實際上是tableview的一部分嗎?像其中一個單元格一樣? – 2014-12-04 18:38:52

+0

不,它不是。主視圖有一個tableview和一個視圖,它有兩個小部件 - textview和一個按鈕。 – user1259574 2014-12-04 18:43:27

+0

你可以發佈你用來移動你的UITextField的代碼嗎? – 2014-12-04 18:46:29

回答

0

我不確定這是否正是您正在尋找的內容,但您可以設置UITextField委託並使用這些委託方法。它們來自我的代碼,但是當鍵盤出現時,它們將視圖框架設置爲動畫,然後在完成時返回。

#pragma mark - Text Editing functions 

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
    [textField resignFirstResponder]; 

    return YES; 
} 


- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    CGRect viewFrame = self.frame; 
    viewFrame.origin.y += animatedDistance; 

    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationBeginsFromCurrentState:YES]; 
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION]; 

    self.frame = viewFrame; 

    [UIView commitAnimations]; 
} 


- (void) textFieldDidBeginEditing:(UITextField*) textField { 
    CGRect textFieldRect = [self.window convertRect:textField.bounds fromView:textField]; 
    CGRect viewRect  = [self.window convertRect:self.bounds fromView:self]; 
    CGFloat midline   = textFieldRect.origin.y + 0.5 * textFieldRect.size.height; 
    CGFloat numerator  = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height; 
    CGFloat denominator  = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height; 
    CGFloat heightFraction = numerator/denominator; 

    if (heightFraction < 0.0) { 
     heightFraction = 0.0; 
    } else if (heightFraction > 1.0) { 
     heightFraction = 1.0; 
    } 

    animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction); 

    CGRect viewFrame = self.frame; 
    viewFrame.origin.y -= animatedDistance; 

    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationBeginsFromCurrentState:YES]; 
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION]; 

    self.frame = viewFrame; 

    [UIView commitAnimations]; 
}