iOS一个容易上手的搜索框,包括模糊查询UISearchDisplayController和UISearchBar交互

          本码农写作能力比较差,希望能给大家用最大努力表达清楚写明白点。很多iOSer对于搜索比较新奇  ,类似于下面这种搜索框,对于新手可能觉得比较新奇(哈哈,别喷我,我只是这么说说)。

好了该说下原理了,搜索和搜索出的关键字,其实就是两个控件的关联,或者说是两个view的交互(一个是搜索框,一个是tableview展示),搜索框和tableview都可以自己定义。

搜索框:。现状常见的搜索框对于iOSer喜欢用UItextfiled,原因很简单,可以设计出比较好看的搜索按钮,也有比较被迫的因为产品狗的axure原型画的乱七八糟(心中一千万个草泥马奔腾而过 )哈哈,不吐槽了。如果公司没有好的原型,UISearchBar

  tableview:我推荐使用UISearchDisplayController这个控件,一句代码做UISearchBar交互。另外他的协议方法就是tableview的协议方法的扩充(iOS8.0后不建议使用这个控件,并不是不可以用),当然小伙伴的你可以做一个tableviewcell展示,根据搜索的内容给出数据进行展示。

所搜的重点:下面说说怎么去搜素的,上面的搜索框和tbaleview这两块砖已经准备好了,现在差水泥。这里有两种方法去搜索:1.下面的图我在所搜框里面输入了d,展示了一堆关于d的数据,如果你的后台哥是好人,你可以发送一个关键字“d”post到服务器,后台进行模糊查询,返回数据展示(常规的app都会这样做)。2,如果是后台一次性返回数据给你,那么iOSer得靠自己搜索,你存到本地把数据源data传到cell,然后根据谓词查找(这里一句概括待会我贴代码)。

我按MVC的设计模式给大家贴上代码块。MVVM一样。

由于写的快 我就一堆乱来。

h文件//

### 代码块

``` objiect -c

#import <UIKit/UIKit.h>

#import "Seachview.h"

#import "SearchableViewCell.h"

@interface ViewController : UIViewController


@property(nonatomic,strong)Seachview *Seachview;


@end

m文件//


#import "ViewController.h"

#import "SearchableViewCell.h"

#define KScreenWidth [UIScreen mainScreen].bounds.size.width

#define KScreenHeight [UIScreen mainScreen].bounds.size.height

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


/*

 

 * 定义data 

 @breaf UISearchDisplayController的数据源

 *

 *

 *

 **/

    NSArray *data;

    NSArray *filterData;


    UISearchDisplayController *searchDisplayController;

    NSString *texname;

    UISearchBar *seachbar;

    BOOL a;

}


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];


    [self layoutUI];

    

    [self creattableview];

    

    // _data = @[@"北京",@"长沙",@"sdfghj中国",@"2345435",@"dedsfsdgg"];


    filterData = self.Seachview.data;

    

    data = self.Seachview.data;

 


    

}



#pragma mark - 界面布局

- (void)layoutUI{

    

/*seachbar 为搜索框

 *Seachview 为关联的一个tbaleview

 */

    seachbar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 44)];

    seachbar.delegate = self;

    

    self.Seachview = [[Seachview alloc] initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];

    

//    取消按钮是否设置

    seachbar.showsBookmarkButton = YES;


    UITextField *field = [[seachbar subviews ] lastObject];


    

    seachbar.barStyle = UIBarStyleDefault;

    seachbar.keyboardType = UIKeyboardTypeDefault;

    seachbar.placeholder = @"搜索";


   

    _Seachview.tableHeaderView = seachbar;

    

    //  searchbar 初始化 SearchDisplayController

    // 并把 searchDisplayController 和当前 controller 关联起来

//    

    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:seachbar contentsController:self];

    


    


    searchDisplayController.searchResultsDataSource = self;

    // searchResultsDelegate 就是 UITableViewDelegate

    searchDisplayController.searchResultsDelegate = self;

    

    searchDisplayController.delegate = self;

    

    

    

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

- (instancetype)init{

    

    self = [super init];

    if (self) {

        

        [self creattableview];

    }

    

    return self;

}

- (void)creattableview{

    



    [self.view addSubview:self.Seachview];

    

    

    

}


#pragma mark -UISearchBardelegete

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{


    NSLog(@"任务编辑文本");

    return YES;

}// return NO to not become first responder

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

    

    NSLog(@"开始");

}                     // called when text starts editing

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{

    

    return YES;

}                       // return NO to not resign first responder

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

    

    NSLog(@"编辑完成");

    

}                       // called when text ends editing

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


    texname = searchText;


    

    NSLog(@"%@",searchText);

}


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

//    [searchDisplayController setActive:NO animated:YES];


    NSLog(@"点击完成");


}                    // called when keyboard search button pressed

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

    

    


    return YES;


}

#pragma mark -


/*

 * 如果原 TableView  SearchDisplayController 中的 TableView delete 指向同一个对象

 * 需要在回调中区分出当前是哪个 TableView

 */

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

{

    if (tableView == self.Seachview) {

//        tableView.rowHeight = 100;

        return data.count;

    }else{

        // 谓词搜索

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self contains [cd] %@",searchDisplayController.searchBar.text];

        filterData =  [[NSArray alloc] initWithArray:[data filteredArrayUsingPredicate:predicate]];

#warning 设置搜索的高度  不要随便该  bug;

        tableView.rowHeight = 100;


        return filterData.count;


    }

}


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

{

    static NSString *cellId = @"mycell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];

    


    

    if (cell == nil) {

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

    }

    

    if (tableView == self.Seachview) {

        cell.textLabel.text = data[indexPath.row];

    }else{

//        tableView.hidden = NO;

        cell.textLabel.text =filterData[indexPath.row];

    }

    

    return cell;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    

    return 1;

    

}

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

    



    NSLog(@"%@",filterData[indexPath.row]);

    seachbar.text =filterData[indexPath.row];


    [searchDisplayController setActive:NO animated:YES];


    

}

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {

    

    searchDisplayController.searchBar.backgroundColor = [UIColor whiteColor];

    

    searchDisplayController.searchBar.showsCancelButton = YES;

    

    for (id searchbutton in seachbar.subviews)

        

    {

        

        UIView *view = (UIView *)searchbutton;

        

        UIButton *cancelButton = (UIButton *)[view.subviews objectAtIndex:2];

        

        cancelButton.enabled = YES;

        

        [cancelButton setTitle:@"取消"  forState:UIControlStateNormal];//文字

        

        break;

        

    }

}

#pragma mark - 把英文的无结果改成中文

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

    

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.001);

    

    dispatch_after(popTime, dispatch_get_main_queue(), ^{

        

        for (UIView *subview in searchDisplayController.searchResultsTableView.subviews) {

            

            if ([subview isKindOfClass:[UILabel class]] && [[(UILabel *)subview text] isEqualToString:@"No Results"]) {

                

                UILabel *label = (UILabel *)subview;

                

                label.text = @"无结果";

                

                break;

                

            }

            

        }

        

    });

    

    return YES;

    

}

###脚注生成一个脚注[^footnote]. [^footnote]: 这里是 **脚注***内容*.

效果图



下面这是网络请求做的 大家可以自己尝试去做





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值