如何在UINavigationBar上添加UISearchBar以及UISearchDisplayController的使用 --OC --iOS


那我們開始吧,下面是Sely寫的一個Demo,分享給大家。

新建一個項目, UISearchDisplayController 的 displaysSearchBarInNavigationBar太死板了,達不到想要的效果。
這里進行重新定制, 四個協議, 三個成員變量,第一步OK。

@interface ViewController ()<UISearchBarDelegate,UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate>

{

    UISearchBar *mySearchBar;

    UISearchDisplayController *mySearchDisplayController;

    NSMutableArray *suggestResults;

}

@end

 

//下面我們來初始化我們的三個成員

-(void)initMysearchBarAndMysearchDisPlay

{

    mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, [UIApplicationsharedApplication].statusBarFrame.size.height, [UIScreen mainScreen].bounds.size.width, 44)];

    mySearchBar.delegate = self;

    //設置選項

    mySearchBar.barTintColor = [UIColor redColor]; 

    mySearchBar.searchBarStyle = UISearchBarStyleDefault;

    mySearchBar.translucent = NO; //是否半透明

    [mySearchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];

    [mySearchBar sizeToFit];

    

    mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self];

    mySearchDisplayController.delegate = self;

    mySearchDisplayController.searchResultsDataSource = self;

    mySearchDisplayController.searchResultsDelegate = self;

    

    suggestResults = [NSMutableArray arrayWithArray:@[@"此處為推薦詞", @"也可以為歷史記錄"]];

 

}

//然后呢當然是自定義我們的navigation bar了

-(void)initNavigationBar

{

    UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];

    [moreButton setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];

    [moreButton addTarget:self action:@selector(handleMore:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *moreItem = [[UIBarButtonItem alloc] initWithCustomView:moreButton];

    

    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];

    [searchButton setImage:[UIImage imageNamed:@"info_search"] forState:UIControlStateNormal];

    [searchButton addTarget:self action:@selector(startSearch:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:searchButton];

    self.navigationItem.rightBarButtonItems = @[moreItem, searchItem];

}

//好了, 開始加載界面了

- (void)viewDidLoad

{

    [super viewDidLoad];

    [self initNavigationBar];

    [self initMysearchBarAndMysearchDisPlay];

 } 

//實現我們的點擊事件

#pragma mark - handle button click

-(void) startSearch:(id)sender

{

    [self.navigationController.view addSubview:mySearchBar];

    [mySearchBar becomeFirstResponder];

}

-(void) handleMore:(id)sender

{}

//實現我們的table view 的協議,判斷當我們開始搜索時,轉到自己實現的一個searchDisplayController方法里,這樣代碼看起來是不是很簡潔?

#pragma mark - UITableViewDataSource & UITableViewDelegate

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    if (tableView == mySearchDisplayController.searchResultsTableView)

    {

        return [self numberOfRowsWithSearchResultTableView];

    }

    return 0;

}

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (tableView == mySearchDisplayController.searchResultsTableView)

    {

        return [self searchTableView:mySearchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath];

    }

    else

    {

        static NSString *cellID = @"search_cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

        if (cell == nil)

        {

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

        }

        return cell;

    }

}

//這里專門寫UISearchDisplayController 中 searchResultsTableView 的 data source 和 delegate

#pragma mark - UISearchDisplayController   <UITableViewDataSource> dataSource

-(NSInteger)numberOfRowsWithSearchResultTableView

{

    return suggestResults.count + 1;

}

-(UITableViewCell*)searchTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *suggestId = @"suggestCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:suggestId];

    if (cell == nil)

    {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:suggestId];

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }

    if (indexPath.row == suggestResults.count)

    {

        cell.textLabel.text = [NSLocalizedString(@"Search: ", @"查找: ") stringByAppendingString:mySearchBar.text];

    }

    else

    {

        cell.textLabel.text = [suggestResults objectAtIndex:indexPath.row];

    }

    return cell;

}

#pragma mark - UISearchDisplayController <UITableViewDelegate> delegate

-(void) searchTableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString *keyword = nil;

    if (indexPath.row == suggestResults.count)

    {

        keyword = mySearchBar.text;

    }

    else

    {

        keyword = [suggestResults objectAtIndex:indexPath.row];

    }

    [mySearchBar resignFirstResponder]; 

}

//開始我們的search bar delegate,輸入搜索內容, 因為是Demo ,所以我並沒有搜索結果,這個大家根據需求自己實現吧

#pragma mark - UISearchBarDelegate

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar

{

    return YES;

}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar

{   

}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

{

    [mySearchDisplayController.searchResultsTableView reloadData];

 

}

 

//最后的環節了, 這個地方的邏輯就會千變萬化了

#pragma mark - UISearchDisplayDelegate

- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0)

{

    //開始搜索事件,設置searchResultsTableView的contentInset,否則位置會錯誤

    mySearchDisplayController.searchResultsTableView.contentInset = UIEdgeInsetsMake(mySearchBar.frame.size.height, 0, 0, 0);  

}

- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableViewNS_DEPRECATED_IOS(3_0,8_0)

{    

    //加載searchResultsTableView完畢

}

- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0)

{

    //結束搜索事件,移除mySearchBar

    [mySearchBar removeFromSuperview]; 

}

// return YES to reload table. called when search string/option changes. convenience methods on top UISearchBar delegate methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString*)searchString NS_DEPRECATED_IOS(3_0,8_0)

{

    //是否需要刷新searchResultsTableView

    if(@"符合條件")

    {

return YES;

    }

    return NO;

 

}

 

就到這里結束,是不是很容易? 這是第一次發布,如果做的不好,請大神指正,如果文筆不好(估計是肯定的),也請多指教,最后希望能多多幫助到大家。

源碼地址

Sely 原創

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM