2014-12-04 40 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]; 
}