UISearchController dimsBackgroundDuringPresentation仅在搜索文本为空时

Mis*_*ssa 9 objective-c uisearchbar ios uisearchcontroller

我有UISearchController和UITableView.viewDidLoad中的代码是:

self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = YES;
[self.searchController.searchBar sizeToFit];
self.searchController.searchBar.delegate = self;
self.searchController.delegate = self;

self.tableView.tableHeaderView = self.searchController.searchBar;
self.tableView.userInteractionEnabled = YES;
Run Code Online (Sandbox Code Playgroud)

我希望每当我点击搜索栏时都会出现灰色视图,当我开始输入时,灰色视图会消失并显示tableView,这样我就可以点击单元格.这意味着仅当搜索栏为空时才会显示灰色视图(就像邮件和联系人应用程序中的默认搜索行为一样).我试着设置

self.searchController.dimsBackgroundDuringPresentation 
Run Code Online (Sandbox Code Playgroud)

在基于searchBar.text的委托方法中

-(void )searchBarTextDidBeginEditing:(UISearchBar *)searchBar
Run Code Online (Sandbox Code Playgroud)

但它不起作用.有任何想法吗?

谢谢,

Sab*_*esh 1

当表格显示并设置灰色和 Alpha 时,我为表格添加了子视图。当 Dismiss SearchController 删除子视图时。我将 dim 属性设置为 false。我的代码如下,可能会对您有所帮助。我使用相同的表格来显示搜索结果。

// on header file
UIView *dimView = null; 

//on .m file

       // create DimView for SearchControl
    - (void)showDimView
    {
        if(dimView == nil && self.searchController.active)
        {
            CGRect rcReplacementView = self.tableView.frame;
            dimView = [[UIView alloc] initWithFrame:rcReplacementView];
            dimView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            dimView.backgroundColor  = [UIColor blackColor];
            dimView.alpha = 0.5;
            [self.view addSubview:dimView];
            self.tableView.scrollEnabled = NO;

            //tap event for hide seachcontroll 
            UITapGestureRecognizer *singleFingerTap =
            [[UITapGestureRecognizer alloc] initWithTarget:self
                                                    action:@selector(handleSingleTap:)];
            [dimView addGestureRecognizer:singleFingerTap];
            [singleFingerTap release];
        }
    }

//close SearchController if Tap on view
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer {

    if(searchController.searchBar.text.length <= 0)
    {
        [self.searchController setActive:NO];
    }
}

// do something before the search controller is dismissed
- (void)willDismissSearchController:(UISearchController *)searchController {

    if(dimView != nil)
    {
        [dimView removeFromSuperview];
        dimView = nil;
    }
    self.tableView.scrollEnabled = YES;
}
Run Code Online (Sandbox Code Playgroud)