如何在没有Interface Builder的UIViewController中实现UISearchDisplayController

Oys*_*sio 9 iphone cocoa-touch uiviewcontroller uisearchdisplaycontroller

我有一个UIViewController分组UITableView为属性.我实例化UITableView代码,不使用IB.我想联系UISearchDisplayController它,但无法找到任何可以做到这一点的例子.

这就是我所拥有的.//已在头文件中实现了UISearchDisplayDelegate

//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];
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用,searchDisplayController UIViewController似乎是readonly并且我无法挂钩myDisplayController它.我真的不确定这是否是正确的方法.

我一直在寻找谷歌周围的一些提示或教程如何使用UISearchDisplayControllerin UIViewController.我能找到的所有例子都是如何将它实现为UITableViewController使用IB,这不是我想要使用它的方式.

任何人都可以解释我怎么能让这个工作?

Ray*_*eck 23

这是我使用的代码.把它放在一个UIViewController的viewDidLoad中,它实例化它自己的UITableView.我认为您正在寻找的部分是将搜索栏添加为表格视图的标题视图.

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];
Run Code Online (Sandbox Code Playgroud)


zgj*_*jie 5

请参阅Apple文档:

@property(nonatomic, readonly, retain) UISearchDisplayController *searchDisplayController
Run Code Online (Sandbox Code Playgroud)

讨论:此属性反映您在Interface Builder中设置的searchDisplayController插座的值.如果以编程方式创建搜索显示控制器,则在初始化时,搜索显示控制器会自动设置此属性.