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

我将如何去做呢?目前,我的搜索栏已通过IB放置在视图中。

谢谢

最佳答案

我建议为键盘显示/隐藏通知添加一个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];
}

关于iphone - 激活后如何扩展UISearchBar,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14235452/

10-16 15:08