2012-01-18 60 views
1

我有一个UITableViewController,我想在顶部添加一个UISearchBarController,所以它使用不同的表视图(而不是UITableViewController的表视图)进行搜索。将UISearchBarController添加到UITableViewController没有IB

如何通过代码初始化此代码而不需要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; 
} 

enter image description here

回答

3

粗略浏览一下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 ...; 
} 
+0

谢谢,我添加了一些代码的问题。我做对了吗? – Jon 2012-01-18 21:00:10

+0

这一切看起来都是正确的,只不过我会在'-viewDidLoad'中执行设置以保证您添加的表视图不为零。另外,您不需要像'initWithSearchBar:contentController:'处理那样分配'self.searchDisplayController'。传入'contentController'的控制器会自动拥有它的'searchDisplayController'属性集。 – 2012-01-18 21:27:40

+0

我现在确定我的IB应该是什么样子,我决定在IB中完成。基本上,我有一个4行的tableview,4行中的每一行都起着搜索的过滤器的作用。点击4行时有一个复选标记。然后当你搜索时,它会显示结果。我得到了一切工作,除了搜索后更新tableview。你能告诉我,如果我走在正确的道路上吗?我已经上传了IB文件格式的图片。 – Jon 2012-01-18 22:29:34

0

你应该看看在here

这个问题已经被询问和回答。我希望这有帮助。

相关问题