2012-01-01 49 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