我在包含项目列表的视图控制器中放置了一个表格视图。
[我在第一张图片中显示的导航栏中放了一个搜索图标。当我点击该图标时,会打开一个搜索栏并显示一个取消按钮。取消按钮正在运行。][1]
现在我想在搜索框中搜索。请任何人都可以帮助我获取代码。
在viewDidLoad中:
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch:)];
self.navigationController.navigationBar.topItem.rightBarButtonItem = searchButton;
toggleSearch:
- (IBAction)toggleSearch:(id)sender
{
_searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
_searchBar.delegate=self;
[_searchBar sizeToFit];
searchController= [[UISearchController alloc]initWithSearchResultsController:self];
searchController.searchResultsUpdater = self;
searchController.searchResultsUpdater = self;
searchController.delegate = self;
self.navigationItem.titleView = searchController.searchBar;
searchController.hidesNavigationBarDuringPresentation = NO;
}
答案 0 :(得分:0)
您需要实现搜索栏委托方法。
首先,您可以将主阵列分配给临时阵列,之后可以添加此代码。
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
[_searchBar setShowsCancelButton:YES animated:YES];
return YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSPredicate *result=[NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@",searchText];
NSArray * array = [arrTemp filteredArrayUsingPredicate:result];
arrMain=[array mutableCopy];
[tblview reloadData];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[_searchBar setShowsCancelButton:NO animated:YES];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
NSPredicate *result=[NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@",searchBar.text];
NSArray * array = [arrTemp filteredArrayUsingPredicate:result];
arrMain=[array mutableCopy];
[tblview reloadData];
[searchBar resignFirstResponder];
[_searchBar setShowsCancelButton:NO animated:YES];
}