您的位置:首页 > 产品设计 > UI/UE

通过 UIKeyboardWillShowNotification 捕获软键盘事件 一个搜索效果的实现

2013-02-22 14:18 375 查看
iPhone内置的Safari程序,点URL条,键盘和URL条中间部分变灰显示,然后随着URL的输入,在中间以UITableView显示搜索的结果。好多iPhone程序也都有类似的效果。这是如何实现的呢?下面说一下我的实现方法。

首先注册键盘事件UIKeyboardWillShowNotification的监听

[[NSNotificationCenter defaultCenter] addObserver:self 

                                            selector:@selector(keyboardWillShow:) 

                                                name:UIKeyboardWillShowNotification object:nil]; 

程序在点击textField或searchBar,键盘显示之前,会发送UIKeyboardWillShowNotification通知消息到我们注册的对象。在keyboardWillShow方法里,我们可以在要变灰的位置上加一个背景着色为黑色的UIView,并将其alpha属性设为0.9,以达到效果

- (void)keyboardWillShow:(NSNotification*)aNotification {

    if (keyboardShown) 

        return; 

    NSDictionary* info = [aNotification userInfo]; 

    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey]; 

    //键盘的大小

    CGSize keyboardRect = [aValue CGRectValue].size;

    //计算覆盖上去的UIView的区域,因为键盘始终是在上面的,所以UIView *maskView下面可以大些,主要不要盖住上面的searchBar之类的内容。要显示结果的UITableView的大小则要根据键盘的大小算出确切的中间区域

    ...

    //将maskView移动最前面

    [window bringSubviewToFront:maskView];

    maskView.alpha = 0.0;

    //设置动画和maskView最终的alpha值

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:0.5];

    maskView.alpha = 0.9;

    [UIView commitAnimations];

    keyboardShown = YES; 

}

keyboardShown是用来跟踪键盘是否已经显示的布尔变量。如果有多个文本域,之间切换时虽然键盘不变,仍会生成UIKeyboardWillShowNotification。通过变量keyboardShown跟踪键盘是不是真的隐藏,可以保证这个效果只执行一次。

当searchBar有输入时,可参考官方例子TableSearch,把UITableView加到上面的maskView上。

当键盘隐藏时,把UITableView移掉,将maskView的alpha属性设为0,即可隐藏maskView。

实现方法可以更灵活,大体思路应该就是这样吧。

转自:http://hi.baidu.com/programme/blog/item/6f8e4c08359015920b7b8249.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐