一個(gè)搜索效果的實(shí)現(xiàn)
2008-11-02 14:11
iPhone內(nèi)置的Safari程序,點(diǎn)URL條,鍵盤(pán)和URL條中間部分變灰顯示,然后隨著URL的輸入,在中間以UITableView顯示搜索的結(jié)果。好多iPhone程序也都有類(lèi)似的效果。這是如何實(shí)現(xiàn)的呢?下面說(shuō)一下我的實(shí)現(xiàn)方法。
首先注冊(cè)鍵盤(pán)事件UIKeyboardWillShowNotification的監(jiān)聽(tīng)
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
程序在點(diǎn)擊textField或searchBar,鍵盤(pán)顯示之前,會(huì)發(fā)送UIKeyboardWillShowNotification通知消息到我們注冊(cè)的對(duì)象。在keyboardWillShow方法里,我們可以在要變灰的位置上加一個(gè)背景著色為黑色的UIView,并將其alpha屬性設(shè)為0.9,以達(dá)到效果
- (void)keyboardWillShow:(NSNotification*)aNotification {
if (keyboardShown)
return;
NSDictionary* info = [aNotification userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
//鍵盤(pán)的大小
CGSize keyboardRect = [aValue CGRectValue].size;
//計(jì)算覆蓋上去的UIView的區(qū)域,因?yàn)殒I盤(pán)始終是在上面的,所以UIView *maskView下面可以大些,主要不要蓋住上面的searchBar之類(lèi)的內(nèi)容。要顯示結(jié)果的UITableView的大小則要根據(jù)鍵盤(pán)的大小算出確切的中間區(qū)域
...
//將maskView移動(dòng)最前面
[window bringSubviewToFront:maskView];
maskView.alpha = 0.0;
//設(shè)置動(dòng)畫(huà)和maskView最終的alpha值
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
maskView.alpha = 0.9;
[UIView commitAnimations];
keyboardShown = YES;
}
keyboardShown是用來(lái)跟蹤鍵盤(pán)是否已經(jīng)顯示的布爾變量。如果有多個(gè)文本域,之間切換時(shí)雖然鍵盤(pán)不變,仍會(huì)生成UIKeyboardWillShowNotification。通過(guò)變量keyboardShown跟蹤鍵盤(pán)是不是真的隱藏,可以保證這個(gè)效果只執(zhí)行一次。
當(dāng)searchBar有輸入時(shí),可參考官方例子TableSearch,把UITableView加到上面的maskView上。
當(dāng)鍵盤(pán)隱藏時(shí),把UITableView移掉,將maskView的alpha屬性設(shè)為0,即可隱藏maskView。
實(shí)現(xiàn)方法可以更靈活,大體思路應(yīng)該就是這樣吧。
轉(zhuǎn)自:http://hi.baidu.com/programme/blog/item/6f8e4c08359015920b7b8249.html
|
@import url(http://www.shnenglu.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);