2012-01-01 52 views
11

我試圖以編程方式創建UISearchDisplayController。我有一個方法應該設置我的搜索控制器,但是當我調用它時,什麼也沒有發生。以編程方式創建UISearchDisplayController

這是我-setupSearch方法:

- (void)setupSearch { 
    UISearchBar *myBar; 
    UISearchDisplayController *myCon; 

    myBar = [[UISearchBar alloc] initWithFrame:CGRectZero]; 
    [myBar sizeToFit]; 

    myCon = [[UISearchDisplayController alloc] 
      initWithSearchBar:myBar contentsController:self]; 
    [myBar release]; 

    myCon.delegate = self; 
    myCon.searchResultsDataSource = self; 
    myCon.searchResultsDelegate = self; 

    /* Setup scopes */ 
    { 
     NSMutableArray *scopes; 
     NSUInteger count, i; 
     NSString *aScope; 

     count = SCOPE_COUNT; 
     scopes = [[NSMutableArray alloc] initWithCapacity:count]; 
     for(i = 0; i < count; i++) { 
      // I create four scopes here 
     } 

     myCon.searchBar.scopeButtonTitles = scopes; 
     [scopes release]; 
    } 

    [myCon release]; 
} 

我稱之爲我的子類UITableViewController-viewDidLoad方法上面的方法。不幸的是,當我的表格視圖控制器被顯示在UITabBarController中時,沒有任何反應。

任何幫助將不勝感激。

回答

12

退房的示例代碼: [ https://github.com/JayMarshal/GrabCasts.com-iPhone-Client/blob/master/CoreDataTableViewController.m][1]

回購在這裏:https://github.com/JayMarshal/Grabcasts

這是斯坦福iOS的課程coredatatableviewcontroller的擴展版本。

該代碼的相關片段如下:

- (void)createSearchBar { 
if (self.searchKey.length) { 
    if (self.tableView && !self.tableView.tableHeaderView) { 
     UISearchBar *searchBar = [[[UISearchBar alloc] init] autorelease]; 
     self.searchDisplayController 
       = [[UISearchDisplayController alloc] initWithSearchBar:searchBar 
                contentsController:self]; 
     self.searchDisplayController.searchResultsDelegate = self; 
     self.searchDisplayController.searchResultsDataSource = self; 
     self.searchDisplayController.delegate = self; 
     searchBar.frame = CGRectMake(0, 0, 0, 38); 
     self.tableView.tableHeaderView = searchBar; 
    } 
} else { 
    self.tableView.tableHeaderView = nil; 
} 

基本上它附着的UISearchDisplayController自我(它必須是一個tableviewcontroller)作爲初始化的副作用。所以設置:

self.searchDisplayController.searchResultsDelegate = self; 
self.searchDisplayController.searchResultsDataSource = self; 

而不是

myCon.searchResultsDataSource = self; 
myCon.searchResultsDelegate = self; 

可能做的伎倆。在調試時,檢查myCon和self.searchDisplayController是否指向同一個對象?

更新:TVC的SDC屬性中似乎存在一個錯誤,它不會保留在runloop中。提起:http://openradar.appspot.com/10254897也在SO上提到,請參閱 UIViewController does not retain its programmatically-created UISearchDisplayController

+1

從doc中,對contentsController:「這通常是UITableViewController的一個實例。」。通常,不是必需的。 – 2013-05-03 21:56:05

+0

所以,如果你不想使用'UITableViewController',你可以簡單地擁有一個符合UITableViewDataSource和UITableViewDelegate協議的'UIViewController'。 – 2013-10-03 16:02:12

+6

我的問題是'self.searchDisplayController'是'UITableViewController'上的只讀屬性,但是這裏的代碼正在設置它。 – 2014-04-03 00:36:14