我在导航控制器内有一个简单的表格视图,工具栏可见。工具栏上有一个搜索按钮,表格视图的表头视图设置为我的UISearchBar
。如果我向上滚动表格视图,然后点击搜索栏将其激活,一切都会正常发生。但是,如果我点击搜索按钮(以编程方式激活搜索栏),则与搜索栏的所有交互都会被禁用(看起来像是被某些东西阻止),并且用户无法清除搜索、取消搜索,甚至无法导航文本字段中的文本。
-(void)viewDidLoad
{
[self setupSearchBar];
}
-(void)setupSearchBar
{
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44.0)];
self.searchBar.autocorrectionType = UITextAutocorrectionTypeDefault;
self.searchBar.delegate = self;
self.tableView.tableHeaderView = self.searchBar;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar
contentsController:self];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
[self.searchController.searchResultsTableView registerNib:[UINib nibWithNibName:@"ItemCell" bundle:nil]
forCellReuseIdentifier:CellIdentifier];
for (UIView* subview in self.searchBar.subviews) {
if ([subview conformsToProtocol:@protocol(UITextInputTraits)]) {
[(UITextField*)subview setKeyboardAppearance:UIKeyboardAppearanceAlert];
[(UITextField*)subview setReturnKeyType:UIReturnKeyDone];
}
}
self.tableView.contentOffset = CGPointMake(0, self.searchBar.frame.size.height);
}
-(IBAction)search:(id)sender
{
[self.searchBar becomeFirstResponder]; // also tried [self.searchController setActive:YES animated:YES];
}
我已经设置了我的搜索显示控制器NSFetchedResultsController
就像描述的那样这个帖子。 https://stackoverflow.com/a/4481896/1827743
UPDATE
我通过使我的UITableView
在设置之前滚动到顶部UISearchBar
给第一响应者。为什么这有效?我不知道,看到成为第一响应者部分不是问题,但如果在成为第一响应者时搜索栏不在屏幕上,则取消和清除按钮将不起作用。这是我现在的代码。
-(void)search:(id)sender
{
[self.tableView setContentOffset:CGPointMake(0, -self.tableView.contentInset.top) animated:NO];
double delayInSeconds = 0.1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self.searchController setActive:YES animated:YES];
[self.searchController.searchBar becomeFirstResponder];
});
}
如果有人对它为何有效有任何见解,我会洗耳恭听。