3

我在导航控制器中有一个简单的表格视图,工具栏可见。工具栏上有一个搜索按钮,表视图的表头视图设置为 my 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];
} 

我已经设置了我的搜索显示控制器,与此 SO 帖子NSFetchedResultsController中描述的类似。

更新

我通过在设置第一响应者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];
    });
}

如果有人对为什么这样做有任何见解,我会全神贯注。

4

1 回答 1

0

尝试执行命中测试,看看您的视线是否被遮挡。

[self.view hitTest:[self.view convertPoint:searchBar.center fromView:searchBar]];

于 2013-10-30T16:41:07.173 回答