如何在UISearchBar变为活动状态时展开

我有一个UISearchBar需要被压缩(见截图),然后扩大到一个更大的大小,当它被触摸或isActive。

我怎么去做这个? 目前我的search栏通过IB放置在视图中。

谢谢

UISearchBar截图

我会build议添加一个NSNotifcation监听器的键盘显示/隐藏通知,并在此基础上调整UISearchBar框架:

- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc addObserver:self selector:@selector(adjustFrame:) name:UIKeyboardWillShowNotification object:nil]; [nc addObserver:self selector:@selector(adjustFrame:) name:UIKeyboardWillHideNotification object:nil]; } 

当视图消失时,我们需要删除监听器:

 - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [nc removeObserver:self name:UIKeyboardWillHideNotification object:nil]; } 

现在我们需要2个自定义函数来调整帧:

 - (void)adjustFrame:(NSNotification *) notification { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3]; [UIView setAnimationBeginsFromCurrentState:YES]; if ([[notification name] isEqual:UIKeyboardWillHideNotification]) { // revert back to the normal state. self.searchBar.frame = CGRectMake (100,50,100,self.searchBar.frame.size.Height); } else { //resize search bar self.searchBar.frame = CGRectMake (10,50,200,self.searchBar.frame.size.Height); } [UIView commitAnimations]; } 

使用这个search栏的代表:

 - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { [self setTheSearchBarWithRect:newRect];//newRect is CGRect; } -(void)setTheSearchBarWithRect:(CGRect)frame{ [UIView animateWithDuration:(1.5f) delay:0 options: UIViewAnimationOptionCurveEaseInOut animations:^{ yourSearchBar.frame = frame; } completion:^(BOOL finished){ }]; } 

并在下面的代表调用上面的函数与其原始框架。

 - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar; - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar; 

您应该在编辑开始和结束时更改search栏框(位置和大小)。

例如:开始

 sbar.frame = CGRectMake(sbar.frame.origin.x - 100., sbar.frame.origin.y, sbar.frame.size.x + 100., sbar.frame.size.y); 

编辑结束时只是在原来的地方控制:

 sbar.frame = CGRectMake(sbar.frame.origin.x + 100., sbar.frame.origin.y, sbar.frame.size.x - 100., sbar.frame.size.y);