当点击图标时导航栏中的搜索栏

问题描述:

我已经在包含项目列表的视图控制器中放置了一个表视图。当点击图标时导航栏中的搜索栏

[我在第一张图片中显示的导航栏中放置了一个搜索图标。当我点击该图标时,搜索栏打开并显示取消按钮。取消按钮正在工作。 ][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; 

} 

您需要实现搜索栏委托方法。

首先,您可以将您的主阵列分配给临时阵列,之后您可以添加此代码。

- (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]; 
}