纯代码创建 UIDisplaySearchController 遇到的问题
这两天需要在程序原有的界面上增加一个搜索地理位置,根据用户选择的地理位置获取对应地点的相关职位的功能。很显然这种界面大家所普遍使用的就是UISearchBar
+UISearchDisplayController
,这种苹果官方的效果不仅很省空间,而且动画以及显示效果都很美观。很早以前就知道有这样一个控件,但是没有用过,今天看了一下API文档,很平常的使用方法:
先创建一个UISearchBar,添加到视图中,设置好代理,并实现必要的代理方法
UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
self.tableView.tableHeaderView = searchBar;
searchBar.delegate = searchBar;
然后再创建一个UISearchDisplayController,把相应的参数传进去,并设置代理,实现必要的代理方法
UISearchDisplayController *searchVC = [[UISearchDisplayController alloc]initWithSearchBar:searchBar contentsController:self];
searchVC.delegate = self;
searchVC.searchResultsDataSource = self;
searchVC.searchResultsDelegate = self;
正常情况下,应该能够在输入文字的时候显示出一个动态的UITableView
,但是,无论我怎么努力,它就是不能正常的显示。
经过一番研究之后,我发现,大多数博客或者教程写的都是用IB实现的,用IB拖进去的话,Xcode
会自动的把UISearchDisplayCountroller
添加到UIViewController
中,如果使用纯代码实现,需要修改一点点东西。
想实现动态的效果,UISearchDisplayCountroller
必须包含UIViewController
中,与之想关联,才能出现动态效果。
而且在UIViewController
中的属性
@property(nonatomic, readonly, retain) UISearchDisplayController *searchDisplayController;
看到了readonly
没,这就是问题所在。
下面我们就来解决这个问题
首先,在视图控制器的.h文件中添加属性:
@property(nonatomic, retain) UISearchDisplayController *searchDisplayController;
可以看到,我们去掉了readonly
然后在.m文件中,添加如下代码:
@synthesize searchDisplayController;
这样,我们再写:
UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
searchBar.delegate = self;
self.tableView.tableHeaderView = searchBar;
self.searchDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:searchBar contentsController:self];
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.searchResultsDelegate = self;
Bingo!!!就可以在输入文字的时候,看到动态的效果啦!