2017-06-28 150 views
0

我已經在包含項目列表的視圖控制器中放置了一個表視圖。當點擊圖標時導航欄中的搜索欄

[我在第一張圖片中顯示的導航欄中放置了一個搜索圖標。當我點擊該圖標時,搜索欄打開並顯示取消按鈕。取消按鈕正在工作。 ][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

您需要實現搜索欄委託方法。

首先,您可以將您的主陣列分配給臨時陣列,之後您可以添加此代碼。

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