搜索控制器框架

PYSearchhttps://github.com/ko1o/PYSearch

 

 

搜索框功能的实现方法有多种:

1.使用UITextField自己封装;

2.UISearchBarController

3.UISearchBar

===========================

举例一:searchBarController实现

 

//UISearchBar,

//属性作用

//UIBarStyle barStyle 控件的样式

//id<UISearchBarDelegate> delegate 设置控件的委托

//NSString *text 控件上面的显示的文字

//NSString *prompt显示在顶部的单行文字,通常作为一个提示行

//NSString *placeholder 半透明的提示文字,输入搜索内容消失

//BOOL showsBookmarkButton 是否在控件的右端显示一个书的按钮(没有文字的时候)

//BOOL showsCancelButton 是否显示cancel按钮

//BOOL showsSearchResultsButton 是否在控件的右端显示搜索结果按钮(没有文字的时候)

//BOOL searchResultsButtonSelected 搜索结果按钮是否被选中

//UIColor *tintColor bar的颜色(具有渐变效果)

//BOOL translucent 指定控件是否会有透视效果

//UITextAutocapitalizationType

//autocapitalizationType 设置在什么的情况下自动大写

//UITextAutocorrectionType

//autocorrectionType 对于文本对象自动校正风格

//UIKeyboardType

//keyboardType 键盘的样式

//NSArray *scopeButtonTitles 搜索栏下部的选择栏,数组里面的内容是按钮的标题

//NSInteger selectedScopeButtonIndex搜索栏下部的选择栏按钮的个数

//BOOL showsScopeBar 控制搜索栏下部的选择栏是否显示出来

//代理列表:

//

//编辑代理

//

//– searchBar:textDidChange:

//– searchBar:shouldChangeTextInRange:replacementText:

//– searchBarShouldBeginEditing:

//– searchBarTextDidBeginEditing:

//– searchBarShouldEndEditing:

//– searchBarTextDidEndEditing:

//点击按钮

//– searchBarBookmarkButtonClicked:

//– searchBarCancelButtonClicked:

//– searchBarSearchButtonClicked:

//– searchBarResultsListButtonClicked:

//范围代理

//– searchBar:selectedScopeButtonIndexDidChange:

//

 

#import "ViewController.h"

 

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

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UISearchController * searchController;

@property (nonatomic,strong) NSArray * carNumberArray;//原始数组

@property (nonatomic,strong) NSArray * filteredArray;//过滤后的数组

@property (nonatomic,strong) NSArray * titleArray;

@property(nonatomic,assign)   BOOL shouldShowSearchResults;//判断是否显示搜索后的数据

@end

 

@implementation ViewController

- (NSArray *)titleArray {

    if (!_titleArray) {

        _titleArray =@[];

    }

    return_titleArray;

}

- (NSArray *)carNumberArray {

    if (!_carNumberArray) {

        _carNumberArray =@[@"qwert",@"qwer",@"qwe",@"qw",@"q"];

    }

    return_carNumberArray;

}

 

- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view from its nib.

    

    

    _tableView = [[UITableViewalloc] initWithFrame:[UIScreenmainScreen].boundsstyle:UITableViewStylePlain];

    _tableView.delegate =self;

    _tableView.dataSource =self;

    

    [self.viewaddSubview:_tableView];

    

    

    self.view.backgroundColor = [UIColorclearColor];

    [selfconfigureSearchController];

    

    

}

- (void)configureSearchController {

    _searchController = [[UISearchControlleralloc] initWithSearchResultsController:nil];

    _searchController.searchResultsUpdater =self;

    _searchController.searchBar.placeholder =@"";

    _searchController.dimsBackgroundDuringPresentation =NO;

    _searchController.searchBar.delegate = self;

    [_searchController.searchBarsizeToFit];

    _searchController.searchBar.showsScopeBar=NO;//第一次数显searchbar时不显示,处于编辑状态(或者获得焦点)时会显示

_searchController.searchBar.scopeButtonTitles=@[@"qqq",@"wwww",@"sss",@"ddd"];

    UIView *v=[[UIViewalloc]initWithFrame:CGRectMake(0,60, 200, 50)];

    v.backgroundColor=[UIColorredColor];

    _searchController.searchBar.inputAccessoryView=v;//弹出键盘时会出现在键盘上方的

    self.tableView.tableHeaderView = _searchController.searchBar;

}

 

//当选择不通的scope时调用

-(void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{

//在这个方法内可以设置搜索

    NSLog(@"scope按钮的索引----%tu",selectedScope);

}

#pragma mark - UISearchBarDelegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {

    self.shouldShowSearchResults =YES;

    

    

    NSLog(@"开始编辑----%tu",searchBar.selectedScopeButtonIndex);

    [self.tableViewreloadData];

}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {

    self.shouldShowSearchResults =NO;

        NSLog(@"取消----%tu",searchBar.selectedScopeButtonIndex);

    [self.tableViewreloadData];

}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    if (!self.shouldShowSearchResults) {

        self.shouldShowSearchResults =YES;

        [self.tableViewreloadData];

    }

 

            NSLog(@"点击search按钮----%tu",searchBar.selectedScopeButtonIndex);

    [self.searchController.searchBarresignFirstResponder];

}

#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    

//        NSLog(@"获取scopeIndex----%tu",searchController.searchBar.selectedScopeButtonIndex);

    //匹配数组

    NSString * searchString = searchController.searchBar.text;

    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",searchString];

    self.filteredArray = [self.carNumberArrayfilteredArrayUsingPredicate:predicate];

    

    [self.tableViewreloadData];

}

#pragma mark - UITableViewDataSource

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

    returnself.shouldShowSearchResults ?self.filteredArray.count :self.carNumberArray.count;

}

 

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

    staticNSString * cellId = @"car_num_cell_id";

    UITableViewCell * cell = [tableViewdequeueReusableCellWithIdentifier:cellId];

    if (!cell) {

        cell = [[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellId];

    }

    if (self.shouldShowSearchResults) {

        cell.textLabel.text =self.filteredArray[indexPath.row];

    }else {

        cell.textLabel.text =self.carNumberArray[indexPath.row];

    }

//    cell.imageView.image = [UIImage imageNamed:@"car.png"];

    

    return cell;

}

#pragma mark - UITableViewDelegate

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

    if (self.shouldShowSearchResults) {

         //搜索之后,可以点击cell跳转

    }else {

        

    }

}

 

 

 

@end

 

 

=============================

 

1.遍历searchBar中的子控件,可以修改子控件属性

// 小技巧: 如果遇到了不认识的类或控件, 可以通过遍历子视图的方式来查看或修改

    //UINavigationButton --> UIButton

    for (UIView *subView in searchBar.subviews.firstObject.subviews) {

        if ([subView isKindOfClass:[UIButton class]]) {

            //NSLog(@"subView:%@",subView);

            

            // 强转类型, 来更改文字

            [(UIButton *)subView setTitle:@"取消" forState:UIControlStateNormal];

        }

2.searchBar的属性设置

 //1.改变背景图片

    [searchBar setBackgroundImage:[UIImageimageNamed:@"bg_login_textfield_hl"]];

    

    //2. 显示取消按钮

    [searchBar setShowsCancelButton:YESanimated:YES];

   //搜索框清空

  searchBar.text=@"";

// 设置searchBar的取消按钮颜色

    self.searchBar.tintColor = [UIColor redColor];

 

 

3.searchBar的代理方法

#pragma mark 当开始编辑的时候会调用

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{}

 

 

#pragma mark 当结束编辑的时候会调用

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{}

 

#pragma mark 取消按钮点击

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar

{

    [self.searchBarresignFirstResponder];//取消编辑状态

}

#pragma mark 文字发生改变时调用的方法

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

{

    NSLog(@"searchText:%@",searchText);

    if (searchText.length) {

        self.citySearchVC.view.hidden =NO;//搜索框有文字时,把原来隐藏的控制器的view显示出来

        // 传递搜索框内的文字

        self.citySearchVC.searchText = searchText;

    } else {

        self.citySearchVC.view.hidden =YES;//搜索框没有文字时,最上面的搜索结果控制器的view隐藏

    }

}

 

 

#pragma mark - SearchBar代理方法

#pragma mark 搜索按钮点击方法

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar

{

    // 只要调用了开始刷新的方法,就可以执行刷新

    [self.collectionView.headerbeginRefreshing];

}

 

//=============================

举例二:UISearchBar实现:

//UISearchBar,

//属性作用

//UIBarStyle barStyle 控件的样式

//id<UISearchBarDelegate> delegate 设置控件的委托

//NSString *text 控件上面的显示的文字

//NSString *prompt显示在顶部的单行文字,通常作为一个提示行

//NSString *placeholder 半透明的提示文字,输入搜索内容消失

//BOOL showsBookmarkButton 是否在控件的右端显示一个书的按钮(没有文字的时候)

//BOOL showsCancelButton 是否显示cancel按钮

//BOOL showsSearchResultsButton 是否在控件的右端显示搜索结果按钮(没有文字的时候)

//BOOL searchResultsButtonSelected 搜索结果按钮是否被选中

//UIColor *tintColor bar的颜色(具有渐变效果)

//BOOL translucent 指定控件是否会有透视效果

//UITextAutocapitalizationType

//autocapitalizationType 设置在什么的情况下自动大写

//UITextAutocorrectionType

//autocorrectionType 对于文本对象自动校正风格

//UIKeyboardType

//keyboardType 键盘的样式

//NSArray *scopeButtonTitles 搜索栏下部的选择栏,数组里面的内容是按钮的标题

//NSInteger selectedScopeButtonIndex搜索栏下部的选择栏按钮的个数

//BOOL showsScopeBar 控制搜索栏下部的选择栏是否显示出来

//代理列表:

//

//编辑代理

//

//– searchBar:textDidChange:

//– searchBar:shouldChangeTextInRange:replacementText:

//– searchBarShouldBeginEditing:

//– searchBarTextDidBeginEditing:

//– searchBarShouldEndEditing:

//– searchBarTextDidEndEditing:

//点击按钮

//– searchBarBookmarkButtonClicked:

//– searchBarCancelButtonClicked:

//– searchBarSearchButtonClicked:

//– searchBarResultsListButtonClicked:

//范围代理

//– searchBar:selectedScopeButtonIndexDidChange:

//

 

#import "ViewController.h"

 

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

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UISearchController * searchController;

@property (nonatomic,strong) NSArray * carNumberArray;//原始数组

@property (nonatomic,strong) NSArray * filteredArray;//过滤后的数组

@property (nonatomic,strong) NSArray * titleArray;

@property(nonatomic,assign)   BOOL shouldShowSearchResults;//判断是否显示搜索后的数据

@end

 

@implementation ViewController

- (NSArray *)titleArray {

    if (!_titleArray) {

        _titleArray =@[];

    }

    return_titleArray;

}

- (NSArray *)carNumberArray {

    if (!_carNumberArray) {

        _carNumberArray =@[@"qwert",@"qwer",@"qwe",@"qw",@"q"];

    }

    return_carNumberArray;

}

 

- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view from its nib.

    

    

    _tableView = [[UITableViewalloc] initWithFrame:[UIScreenmainScreen].boundsstyle:UITableViewStylePlain];

    _tableView.delegate =self;

    _tableView.dataSource =self;

    

    [self.viewaddSubview:_tableView];

    

    

    self.view.backgroundColor = [UIColorclearColor];

    UISearchBar *searchBar=[[UISearchBaralloc]initWithFrame:CGRectMake(50,20, 200,80)];

   //=============

    _tableView.tableHeaderView=searchBar;

    searchBar.showsCancelButton=YES;

    searchBar.delegate=self;

    

  //===============

    

//    UISearchBar *searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(50, 60, 200, 80)];

//    self.searchBar=searchBar;

//    searchBar.tintColor=[UIColor blackColor];//取消按钮的颜色

//    UIButton *cancelBtn=[searchBar valueForKey:@"cancelButton"];

//    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];

//    searchBar.delegate=self;

//    searchBar.placeholder=@"asdf";//搜索框中的提示文字

//    searchBar.returnKeyType=UIReturnKeySearch;//键盘上确定按钮样式

//    //    searchBar.keyboardType=UIKeyboardTypeNumberPad;//键盘样式

//    //    searchBar.showsCancelButton=YES;

//    [self.view addSubview:searchBar];

//    searchBar.showsScopeBar=YES;//searchbar底下显示选择的范围

//    //    searchBar.searchBarStyle=UISearchBarStyleMinimal;

//    searchBar.showsBookmarkButton=YES;//显示书签按钮

//    searchBar.showsSearchResultsButton=YES;//显示搜索结果按钮

//    searchBar.searchResultsButtonSelected=YES;//搜索结果按钮为选中状态

//    searchBar.barStyle=UIBarStyleDefault;//

//    searchBar.text=@"qqqqq";//默认的文本

//    searchBar.prompt=@"wwwww";//searchbar上方的提示文字

    

}

 

#pragma mark - UISearchBarDelegate

//开始编辑的时候调用

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {

    self.shouldShowSearchResults =YES;

    

    [self.tableViewreloadData];

 

    NSLog(@"开始编辑");

}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {

    self.shouldShowSearchResults =NO;

    NSLog(@"取消按钮");

    //点击取消按钮后,就取消了搜索,显示原始的数据

    [self.tableViewreloadData];

}

//点击了搜索按钮

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    NSString * searchString = searchBar.text;

    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",searchString];

    self.filteredArray = [self.carNumberArrayfilteredArrayUsingPredicate:predicate];

    [self.tableViewreloadData];

 

 

    if (!self.shouldShowSearchResults) {

        self.shouldShowSearchResults =YES;

        [self.tableViewreloadData];

    }

    NSLog(@"搜索按钮");

 

}

 

#pragma mark - UITableViewDataSource

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

    returnself.shouldShowSearchResults ?self.filteredArray.count :self.carNumberArray.count;

}

 

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

    staticNSString * cellId = @"car_num_cell_id";

    UITableViewCell * cell = [tableViewdequeueReusableCellWithIdentifier:cellId];

    if (!cell) {

        cell = [[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellId];

    }

    if (self.shouldShowSearchResults) {

        cell.textLabel.text =self.filteredArray[indexPath.row];

    }else {

        cell.textLabel.text =self.carNumberArray[indexPath.row];

    }

//    cell.imageView.image = [UIImage imageNamed:@"car.png"];

    

    return cell;

}

#pragma mark - UITableViewDelegate

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

    if (self.shouldShowSearchResults) {

         //搜索之后,可以点击cell跳转

    }else {

        

    }

}

 

//============searchController代理方法

//- (void)willPresentSearchController:(UISearchController *)searchController{

//    NSLog(@"searchVC将要出现");

//}

//- (void)didPresentSearchController:(UISearchController *)searchController{

//    NSLog(@"searchVC已经出现");

//    

//}

//- (void)willDismissSearchController:(UISearchController *)searchController{

//    NSLog(@"searchVC将要消失");

//}

//- (void)didDismissSearchController:(UISearchController *)searchController{

//    NSLog(@"searchVC 已经消失");

//}

//

//- (void)presentSearchController:(UISearchController *)searchController{

//    NSLog(@"searchBar开始编辑时调用");

//}

//=====================searchBar的代理方法

 

#pragma mark 当结束编辑的时候会调用

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{

    NSLog(@"编辑结束");

}

#pragma mark 文字发生改变时调用的方法

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

{

    NSString * searchString = searchBar.text;

    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",searchString];

    self.filteredArray = [self.carNumberArrayfilteredArrayUsingPredicate:predicate];

    [self.tableViewreloadData];

 

    //可以实时获取输入框中的文字

    NSLog(@"searchText:%@",searchText);

}

 

@end

 


**************搜索控制器框架:https://github.com/ko1o/PYSearch

//搜索控制器
-(void)searchContgroller{
 
    NSArray *hotSeaches = @[@"Java", @"Python", @"Objective-C", @"Swift", @"C", @"C++", @"PHP", @"C#", @"Perl", @"Go", @"JavaScript", @"R", @"Ruby", @"MATLAB"];
   
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:hotSeaches searchBarPlaceholder:@"搜索" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
       //搜索结束回调,跳转到结果控制器
        [searchViewController.navigationController pushViewController:[[LYBsearchResultVC alloc] init] animated:YES];
        
    }];
    searchViewController.delegate=self;
    searchViewController.dataSource=self;
    // 1. Set searchResultShowMode
    searchViewController.searchResultShowMode = PYSearchResultShowModeEmbed;
    // 2. Set searchResultController
    searchViewController.searchResultController = [[UIViewController alloc] init];
 
    // Set hotSearchStyle
    searchViewController.hotSearchStyle = PYHotSearchStyleColorfulTag;
 
    // Set searchHistoryStyle
    searchViewController.searchHistoryStyle = PYSearchHistoryStyleBorderTag;
   
    // Set searchHistoriesCachePath
    searchViewController.searchHistoriesCachePath = @"The cache path";
    
    // Set searchHistoriesCount
    searchViewController. searchHistoriesCount = 6;
  
    // Set searchResultShowMode
    searchViewController.searchResultShowMode = PYSearchResultShowModeEmbed;
   
    // Set searchSuggestionHidden
    searchViewController.searchSuggestionHidden = YES;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    
    [self presentViewController:nav  animated:NO completion:nil];

}

 

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐