当 UISearchBar 处于活动状态时如何展开它 [英] How to expand a UISearchBar when it becomes active
本文介绍了当 UISearchBar 处于活动状态时如何展开它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 UISearchBar 需要压缩(见截图),然后在它被触摸或处于活动状态时扩展到更大的尺寸.
I have a UISearchBar that needs to be compressed (see screenshot) and then expand to a larger size when it is touched or isActive.
我该怎么做?目前我的搜索栏通过 IB 放置在视图中.
How would I go about doing this? Currently my search bar is placed in the view via IB.
谢谢
推荐答案
我建议为键盘显示/隐藏通知添加一个 NSNotifcation 侦听器,并基于此调整 UISearchBar 框架:
I would suggest adding a NSNotifcation listener for the keyboard showing/hiding notifications and based on this adjust the UISearchBar frame:
- (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];
}
当视图即将消失时,我们需要移除监听器:
We need to remove the listener when the view is going to disappear:
- (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 个自定义函数来调整框架:
And now we need the 2 custom functions to adjust the frame:
- (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];
}
这篇关于当 UISearchBar 处于活动状态时如何展开它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文