2012-06-02 32 views
2

背景iOS 5的搜索顯示控制器和的UITableViewController

的重用我有一個iPhone應用程序,通過子每次使用再分級利用了UITableViewController子類的幾個地方。其中一種用途是搜索控制器。

@interface TableViewController : UITableViewController 
// ... 
@interface SearchTableViewController : TableViewController <UISearchDisplayDelegate, UISearchBarDelegate> 

在故事板編輯我在,使得使用的TableViewController每個視圖相同的表視圖,細胞結構,和重用標識符。到處都是我使用的故事板根據我的設計時間原型生成單元格,因此在tableView:cellForRowAtIndexPath:方法中我不必包含if (cell == nil)部分。

問題

我做錯了什麼,而不是由其他人一樣的故事板產生我的搜索控制器的細胞。起初,我在if (cell == nil)位中添加了一個來解決這個問題,但它會導致我的搜索顯示空行。實際上,搜索會顯示正確的空白行數。取消搜索後,結果將從背景中出現。下面是TableViewController代碼:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    ModelObject* obj = [self.dataSource modelAtIndex:indexPath.row]; 
    UILabel* name = (UILabel*) [cell viewWithTag:1]; 
    name.text = obj.name; 
    return cell; 
} 

我懷疑有可能是必要的,以確定問題的其他細節,但是,什麼樣的事情可能會導致這將是有幫助的任何提示。謝謝。

回答

1

如果您正在使用Storyboard,請選擇對象「搜索欄與搜索顯示控制器」並將其放置在您的視圖控制器(比方說VC)中。然後,Xcode將自動將搜索欄鏈接到駐留在VC中的搜索顯示控制器。 因此,在VC,則可以通過self.searchDisplayController 訪問搜索顯示控制器和您的VC應採用的協議,如UISearchBarDelegate, UISearchDisplayDelegate 此外搜索條可以通過self.searchDisplayController.searchBar

訪問實現在UISearchDisplayDelegate協議相對的方法(表視圖等)。答對了!您的搜索結果將自動顯示。

0

「tableview」的部分是錯誤的。

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

您應該使用self.tableview(或者您鏈接到您的tableview的IBOutlet變量名)代替。喜歡這個;

UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

當搜索完成時,cellForRowAtIndexPath中的tableview參數將不是您在viewcontroller中的tableview參數。這是問題的原因。

相關問題