UISearchBar没有被设置为UITableView的tableHeaderView

3

我在通过程序创建UITableView的UISearchBar和UISearchDisplayController方面遇到了问题。我已经设置好了UISearchBar和UISearchDisplayController,然后将self.tableview.tableHeaderView设置为self.searchBar。但是tableHeaderView仍然为NULL,而searchBar和searchDisplayController不是。我该如何使UISearchBar不为null并出现在表头中?

这是我的设置:

- (void)viewDidLoad {
[super viewDidLoad];

/*other things here*/

//Search Bar
self.searchedDancerData = [[NSMutableArray alloc] init];
self.searchBar = [[UISearchBar alloc] init];
self.searchBar.delegate = self;
[self.searchBar sizeToFit];
self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
[self.tableView setTableHeaderView:self.searchBar];
self.tableView.tableHeaderView.frame = CGRectMake(0, 0, tableView.frame.size.width, 44);

self.searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
[self.searchDisplayController setDelegate:self];
[self.searchDisplayController setSearchResultsDataSource:self];
[self.tableView reloadData];
NSLog(@"%@", self.tableView.tableHeaderView); //Returns NULL
}

- (void)viewWillAppear:(BOOL)animated
{
/*other things*/

//set Content offest
[self.tableView setContentOffset:CGPointMake(0, 44)]; 
}

#pragma mark UISearchDisplayControllerDelegate

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self.searchedDancerData removeAllObjects];

for (NSDictionary *dancer in self.dancerData) {
    NSRange range = [[dancer objectForKey:@"Name"] rangeOfString:searchString options:NSCaseInsensitiveSearch];
    if (range.location != NSNotFound) {
        [self.searchedDancerData addObject:[dancer copy]];
        [self.searchedDancerData sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    }
}
return YES;
}

- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
{
[self.searchDisplayController.searchResultsTableView setDelegate:self];
}

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
[self.tableView setContentOffset:CGPointMake(0, 44) animated:YES];
}

-(void)searchBar:(id)sender
{
[self.searchDisplayController setActive:YES animated:YES];
}

我的所有UITableViewDelegate方法都包含以下代码,用于填充搜索表格:

if (self.searchDisplayController.searchResultsTableView == theTableView) {
    return something;
} else {
    return somethingElse
}

我觉得我已经正确设置了这个,有人可以帮帮我吗?

也许尝试设置UISearchBar的框架? - ewiinnnnn
不行,没有起作用。我还尝试在navigationBar中添加一个搜索按钮,当我点击它时,searchDisplayController可以工作,但是searchBar仍然没有出现。 - Brandon Mcq
1个回答

2
尝试将搜索栏设置为UITableView的头视图中UISearchDisplayController的搜索栏。
[self.tableView setTableHeaderView:self.searchDisplayController.searchBar];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接