如何使用UISearchDisplayController预加载或初始化搜索?

Lav*_*der 5 iphone initialization objective-c uisearchdisplaycontroller

我在InterfaceBuilder中的UITableViewController中添加了一个UISearchDisplayController.通过添加searchBar: searchBar textDidChange: searchText为表和调用重新生成数据数组的方法,可以很容易地使其工作reloadData.

但是我想在下次用户触摸搜索栏时显示上一个搜索节目,因为触摸(X)并清除它比再次输入更容易.但我无法做到这一点.以下是我尝试过的代码:

- (void) searchBar: (UISearchBar *) searchBar textDidChange: (NSString *) searchText {
    if( searchText && [searchText length] > 0 ) {
        self.displayedRows = [[NSMutableArray initWithCapacity: 1];
        for( NSString *l in self.allRows ) {
            NSRange r = [l rangeOfString: searchText];
            if( r.location != NSNotFound )
                [self.displayedRows addObject: l];
        }
        [self.searchDisplayController.searchResultsTableView reloadData];
    }
}

- (void) searchDisplayControllerWillBeginSearch: (UISearchDisplayController *) controller {
    if( self.lastSearch && [self.lastSearch length] > 0 ) {
        controller.searchBar.text = self.lastSearch;
        [controller.searchResultsTableView reloadData];
    }
}

- (void) searchDisplayControllerWillEndSearch: (UISearchDisplayController *) controller {
    self.lastSearch = controller.searchBar.text;
    self.displayedRows = self.allRows;
    [self.tableView reloadData];
}
Run Code Online (Sandbox Code Playgroud)

下次我触摸搜索时,最后一个搜索文本在搜索栏中是相应的,我很惊讶"光标"甚至位于末尾,但搜索结果没有显示,只是原始内容的黑暗视图,如搜索字段为空.只要我输入一个字符,搜索结果就会更新.

我已经尝试将相应的内容[self.searchDisplayController.searchResultsTableView reloadData]放入每个中:

searchDisplayControllerDidBeginSearch: (UISearchDisplayController *) controller
searchDisplayController: (UISearchDisplayController *) controller didLoadSearchResultsTableView: (UITableView *) tableView
searchDisplayController: (UISearchDisplayController *) controller willShowSearchResultsTableView: (UITableView *) tableView
searchDisplayController: (UISearchDisplayController *) controller didShowSearchResultsTableView: (UITableView *) tableView
Run Code Online (Sandbox Code Playgroud)

但它没有任何区别......只有空白直到我输入内容.

有没有人有任何想法如何获得预加载的搜索结果?

aqu*_*qua 7

你需要这样的东西:

- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
    if(lastSearch.length > 0) {
        NSLog(@"In searchDisplayControllerDidBeginSearch");
        [self.searchDisplayController.searchBar setText:lastSearch];
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要进行进一步的更改,我建议打开UIKit标题UISearchBar.h,UISearchDisplayController.h然后查看可以重载的内容和位置.另外,NSLog是你的朋友=)

只是为了解释发生了什么,以及这与注册的力量有什么不同...searchBar.text = lastSearch,注册的setText力量textDidChange反过来又重新调整搜索,然后调用shouldReloadTableForSearchString.只是更改文本而不使用setText(由于某种原因)不会触发textDidChange.