9

我有一個UIViewController具有分組UITableView作爲屬性。我在代碼中實例化UITableView並且不使用IB。我想掛鉤UISearchDisplayController但它找不到任何示例如何做到這一點。HOWTO在一個UIViewController實施UISearchDisplayController沒有Interface Builder中

這是我有。 //在頭文件

//SearchBar 
UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 45)]; 
searchBar.barStyle=UIBarStyleBlackTranslucent; 
searchBar.showsCancelButton=NO; 
searchBar.autocorrectionType=UITextAutocorrectionTypeNo; 
searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone; 
searchBar.delegate=self; 


UISearchDisplayController *mySearchDisplayController = [[UISearchDisplayController alloc ]initWithSearchBar:searchBar contentsController:self]; 
self.searchDisplayController = mySearchDisplayController; //Error here ?? self.searchDisplayController is ReadOnly and can't assign 

[self.searchDisplayController setDelegate:self]; 
[self.searchDisplayController setSearchResultsDataSource:self]; 

[mySearchDisplayController release]; 
[myDisplayController release]; 

這似乎並不工作實施UISearchDisplayDelegate的UIViewController的searchDisplayController屬性格式似乎是隻讀的,我不能鉤myDisplayController到它。我真的不確定這是否正確。

我一直在尋找谷歌周圍找到一些提示或教程如何使用UISearchDisplayControllerUIViewController。我能找到的所有例子是如何使用IB實現它到UITableViewController,這不是我想要使用它的方式。

誰能解釋我怎麼能得到這個工作?

回答

23

下面是我使用的代碼。把它放在實例化它自己的UITableView的UIViewController的viewDidLoad中。我認爲你正在尋找的部分是添加搜索欄作爲表視圖的標題視圖。

UISearchBar * theSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,0,320,40)]; // frame has no effect. 
theSearchBar.delegate = self; 
if (!searchBarPlaceHolder) { 
    searchBarPlaceHolder = @"What are you looking for?"; 
} 
theSearchBar.placeholder = searchBarPlaceHolder; 
theSearchBar.showsCancelButton = YES; 


self.theTableView.tableHeaderView = theSearchBar; 

UISearchDisplayController *searchCon = [[UISearchDisplayController alloc] 
             initWithSearchBar:theSearchBar 
             contentsController:self ]; 
self.searchController = searchCon; 
[searchCon release]; 
searchController.delegate = self; 
searchController.searchResultsDataSource = self; 
searchController.searchResultsDelegate = self; 

[searchController setActive:YES animated:YES]; 
[theSearchBar becomeFirstResponder]; 
+4

什麼searchController在你的代碼? – 2012-09-24 08:56:22

+0

這是UISearchDisplayController – Rayfleck 2012-09-24 13:37:34

+0

@luyuan的一個實例:我想'searchController'是'UISearchDisplayController'對象和@Rayfleck忘記談論它。你可以像'UIViewController'的'UISearchDisplayController'一樣創建1個'UISearchDisplayController'對象。它將與'UIViewController'一樣工作 – VietHung 2013-12-04 03:10:34

5

看到蘋果文檔:

@property(nonatomic, readonly, retain) UISearchDisplayController *searchDisplayController 

討論:該屬性反映了您在Interface Builder設置 searchDisplayController出口的價值。如果 編程方式創建搜索顯示控制器,這 屬性是通過時 它被初始化搜索顯示控制器自動設置。

+0

我不明白,「如果您以編程方式創建搜索顯示控制器」,這是什麼意思? – jeswang 2014-10-05 10:41:38

相關問題