以编程方式激活UISearchBar会阻止用户与其进行交互

时间:2013-10-30 16:28:34

标签: ios objective-c uitableview uisearchbar uisearchdisplaycontroller

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

我使用this SO post.

中描述的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];
    });
}

如果有人对其原因有任何见解,我会全力以赴。

1 个答案:

答案 0 :(得分:0)

尝试执行hit test,查看您的观点是否受阻。

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