我有一个需要压缩的UISearchBar(见截图),然后在触摸或isActive时扩展到更大的尺寸。
我该怎么做呢?目前,我的搜索栏通过IB放置在视图中。
感谢
答案 0 :(得分:3)
使用搜索栏的此代表:
- (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;
答案 1 :(得分:2)
我建议为键盘显示/隐藏通知添加一个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];
}
答案 2 :(得分:1)
您应该在编辑开始和结束时更改搜索栏的框架(位置和大小)。
例如: 在开始
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);