1

我有一个 UISearchBar 需要压缩(见屏幕截图),然后在触摸或 isActive 时扩展为更大的尺寸。

我该怎么做呢?目前我的搜索栏通过 IB 放置在视图中。

谢谢

UISearchBar 截图

4

3 回答 3

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;
于 2013-01-09T12:52:25.410 回答
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];
}
于 2013-01-09T12:52:12.533 回答
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);
于 2013-01-09T12:55:02.957 回答