一個搜索效果的實現
2008-11-02 14:11
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
|
@import url(http://www.shnenglu.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);