2012-01-18 58 views
1

我有一個UITableViewController,我想在頂部添加一個UISearchBarController,所以它使用不同的表視圖(而不是UITableViewController的表視圖)進行搜索。將UISearchBarController添加到UITableViewController沒有IB

如何通過代碼初始化此代碼而不需要IB?

@interface mySearchController : UITableViewController <UISearchDisplayDelegate, UISearchBarDelegate> 

@property (nonatomic, retain) UISearchDisplayController *aSearchBarController; 
@property (nonatomic, retain) UISearchBar *aSearchBar; 

@end 

- (id)init { 
    if ((self = [super init])) { 

     UISearchBar *tempSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0)]; 
     self.aSearchBar = tempSearchBar; 
     self.aSearchBar.delegate = self; 
     [self.aSearchBar sizeToFit]; 
     self.tableView.tableHeaderView = self.aSearchBar; 
     [self.aSearchBar release]; 

     UISearchDisplayController *tempSearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:aSearchBar contentsController:self]; 
     self.searchDisplayController = tempSearchDisplayController; 
     self.searchDisplayController.delegate = self; 
     self.searchDisplayController.searchResultsDataSource = self; 
     self.searchDisplayController.searchResultsDelegate = self; 
    } 
    return self; 
} 

- (id)initWithStyle:(UITableViewStyle)style { 
    self = [super initWithStyle:UITableViewStyleGrouped]; 
    if (self) { 
     // Custom initialization. 
    } 
    return self; 
} 

enter image description here

回答

3

粗略瀏覽一下UISearchDisplayController Class Reference會回答你的問題。

「通常從視圖 控制器(通常的UITableViewController的實例)這是 顯示列表初始化一個搜索顯示控制器。爲了編程方式執行配置中,用於搜索顯示控制器的視圖控制器和搜索結果的數據集self來源和委託「。

因此,它應該是這樣的:

searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self]; 
searchController.delegate = self; 
searchController.searchResultsDataSource = self; 
searchController.searchResultsDelegate = self; 

如果按照這種模式,然後在表視圖的數據源和委託方法,您可以檢查方法表視圖參數,以確定哪些表視圖發送消息:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (tableView == self.tableView) 
    { 
     return ...; 
    } 

    // If necessary (if self is the data source for other table views), 
    // check whether tableView is searchController.searchResultsTableView. 
    return ...; 
} 
+0

謝謝,我添加了一些代碼的問題。我做對了嗎? – Jon 2012-01-18 21:00:10

+0

這一切看起來都是正確的,只不過我會在'-viewDidLoad'中執行設置以保證您添加的表視圖不爲零。另外,您不需要像'initWithSearchBar:contentController:'處理那樣分配'self.searchDisplayController'。傳入'contentController'的控制器會自動擁有它的'searchDisplayController'屬性集。 – 2012-01-18 21:27:40

+0

我現在確定我的IB應該是什麼樣子,我決定在IB中完成。基本上,我有一個4行的tableview,4行中的每一行都起着搜索的過濾器的作用。點擊4行時有一個複選標記。然後當你搜索時,它會顯示結果。我得到了一切工作,除了搜索後更新tableview。你能告訴我,如果我走在正確的道路上嗎?我已經上傳了IB文件格式的圖片。 – Jon 2012-01-18 22:29:34

0

你應該看看在here

這個問題已經被詢問和回答。我希望這有幫助。

相關問題