2011-06-01 72 views
11

我想在ObjectiveC中有一個簡單的SearchBar。使用UISearchBarUISearchBarDelegate令我困惑。我本可以使用UITextField,但它沒有&的感覺。設計iOS搜索欄

如附圖所示,我只需要與它關聯的搜索欄沒有UITableView。圖像附有一個TableView,但你明白了。還有人在輸入文字後進入searchBar &按「enter」如何檢索文字?

enter image description here

更新:我知道這些鏈接,其討論相同的,但他們更光使用表格。

http://blog.webscale.co.in/?p=228

http://ved-dimensions.blogspot.com/2009/02/iphone-development-adding-search-bar-in.html

How to implement search bar in iPhone?

UISearchBar Sample Code

UISearchBar in UITableViewController?

+0

檢查http://stackoverflow.com/questions/6201406/how-to-custom-uisearchbar/6201490#6201490 – Jhaliya 2011-06-01 15:21:58

+0

什麼是錯的使用現有的UISearchBar和相關類? – 2011-06-01 15:22:57

+0

您不需要使用表格視圖控制器! – 2011-06-01 15:35:14

回答

33

只是讓你的視圖控制器實現UISearchBarDelegate。在你的xib文件中,你需要做的只是添加一個UISearchBar到你的視圖並根據需要進行配置,爲它創建一個出口(可選,但有助於明確),並將代理插座分配給你的視圖控制器。

然後,爲了響應搜索欄事件,根據需要實施UISearchBarDelegate協議方法。例如:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { 
    [self handleSearch:searchBar]; 
} 

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar { 
    [self handleSearch:searchBar]; 
} 

- (void)handleSearch:(UISearchBar *)searchBar { 
    NSLog(@"User searched for %@", searchBar.text); 
    [searchBar resignFirstResponder]; // if you want the keyboard to go away 
} 

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar { 
    NSLog(@"User canceled search"); 
    [searchBar resignFirstResponder]; // if you want the keyboard to go away 
}