【发布时间】:2013-11-10 09:29:18
【问题描述】:
我在导航控制器中有一个简单的表格视图,工具栏可见。工具栏上有一个搜索按钮,表视图的表头视图设置为我的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 设置了我的搜索显示控制器,如this SO post. 中所述
更新
我通过将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];
});
}
如果有人对为什么这样做有任何见解,我会全力以赴。
【问题讨论】:
-
你的解决方案真棒!你拯救了我的一天.. ;-) 我无法理解,因为它发生了,但它就像另一个 iOS 行为:如果你有一个按钮作为子视图添加到视图中,并且该视图不包含整个按钮框架(例如,因为按钮的框架更大),这个按钮不起作用。所以,我重复一遍,
标签: ios objective-c uitableview uisearchbar uisearchdisplaycontroller