将 UISearchBarController 添加到没有 IB 的 UITableViewController
Posted
技术标签:
【中文标题】将 UISearchBarController 添加到没有 IB 的 UITableViewController【英文标题】:Add UISearchBarController to a UITableViewController Without IB 【发布时间】:2012-01-18 19:24:20 【问题描述】:我有一个 UITableViewController,我想在顶部添加一个 UISearchBarController,以便它使用不同的表视图(而不是 UITableViewController 的表视图)进行搜索。
如何通过代码而不是 IB 来初始化它?
@interface mySearchController : UITableViewController <UISearchDisplayDelegate, UISearchBarDelegate>
@property (nonatomic, retain) UISearchDisplayController *aSearchBarController;
@property (nonatomic, retain) UISearchBar *aSearchBar;
@end
- (id)init
if ((self = [super init]))
UISearchBar *tempSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0)];
self.aSearchBar = tempSearchBar;
self.aSearchBar.delegate = self;
[self.aSearchBar sizeToFit];
self.tableView.tableHeaderView = self.aSearchBar;
[self.aSearchBar release];
UISearchDisplayController *tempSearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:aSearchBar contentsController:self];
self.searchDisplayController = tempSearchDisplayController;
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.searchResultsDelegate = self;
return self;
- (id)initWithStyle:(UITableViewStyle)style
self = [super initWithStyle:UITableViewStyleGrouped];
if (self)
// Custom initialization.
return self;
【问题讨论】:
【参考方案1】:粗略浏览一下UISearchDisplayController Class Reference
即可回答您的问题。
“通常你从一个视图初始化一个搜索显示控制器 控制器(通常是 UITableViewController 的一个实例) 显示列表。要以编程方式执行配置,请为搜索显示控制器的视图控制器和搜索结果数据源和委托设置
self
。"
所以它应该是这样的:
searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchController.delegate = self;
searchController.searchResultsDataSource = self;
searchController.searchResultsDelegate = self;
如果你遵循这个模式,那么在表视图数据源和委托方法中,你可以检查方法的表视图参数以确定哪个表视图正在发送消息:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
if (tableView == self.tableView)
return ...;
// If necessary (if self is the data source for other table views),
// check whether tableView is searchController.searchResultsTableView.
return ...;
【讨论】:
谢谢,我在问题中添加了一些代码。我做得对吗? 这一切看起来都是正确的,除了我会在-viewDidLoad
中执行设置以保证您添加到的表视图是非零的。此外,您不需要分配self.searchDisplayController
,因为它由initWithSearchBar:contentController:
处理。传入contentController
的控制器将自动设置其searchDisplayController
属性。
我现在确定我的 IB 应该是什么样子,我决定在 IB 中做这件事。本质上,我有一个有 4 行的 tableview,4 行中的每一行都用作搜索的过滤器。单击时,这 4 行有一个复选标记。然后,当您搜索时,它会显示结果。除了在搜索后更新 tableview 之外,我一切正常。你能告诉我我是否走在正确的道路上吗?我上传了一张 IB 文件布局的图片。
如果您要过滤几个项目,您可能会放弃所有表格视图并使用搜索栏上的范围按钮。您基本上是在重新实现相同的行为。
我可以这样做,但不幸的是我无法更改 UI。可能是因为过滤器文本较长,您可以选择多个过滤器进行搜索。【参考方案2】:
你应该看看here。
这个问题已经被问过和回答了。我希望这会有所帮助。
【讨论】:
以上是关于将 UISearchBarController 添加到没有 IB 的 UITableViewController的主要内容,如果未能解决你的问题,请参考以下文章
UISearchBarController 在调用返回按钮后不隐藏
将 Lambda 函数添加到 AWS AppSync 数据源?
如何以编程方式将 selectableItemBackground 添加到 ImageButton?