iOS开发 -UISearchController的使用和改善方法

812 阅读3分钟

效果图
这里写图片描述
搜索栏在开发中算是比较常见的了,而系统的searchbar很多人并不是很喜欢用,最近博主无意间看到一个系统的searchbar,觉得看着很漂亮,所以就自己来写写,其实设置placeholder,颜色,搜索logo,触发搜索操作都是存在的,看起来也很漂亮,以下是博主写的代码:


#import <UIKit/UIKit.h>

@protocol SearchInputtingDelegate <NSObject>

- (void)searchMyInput:(NSString *)inputStr;

@end

@interface ViewController : UIViewController

@property(nonatomic,weak)id<SearchInputtingDelegate>delegate;

@end

.m
#import "ViewController.h"
#import "SearchResultViewController.h"



@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
{
    UITableView *_tableView;
    UIBarButtonItem *_navRightButton;
}
@property (nonatomic, strong) SearchResultViewController *searchVC;
@property (nonatomic, strong) UISearchController *searchController;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setHidesBottomBarWhenPushed:NO];


    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [self initMySearchBar];
}

/**
 *  初始化子视图
 */
- (void) initMySearchBar
{
    // 搜索页
    _searchVC = [[SearchResultViewController alloc] init];
    //遵守代理,用于后面传值
    self.delegate = _searchVC;
    _searchController = [[UISearchController alloc] initWithSearchResultsController:_searchVC];
    //设置后可以看到实时输入内容,可以在结果页的代理里面设置输入长度
    [_searchController setSearchResultsUpdater: _searchVC];
    [_searchController.searchBar setPlaceholder:@"搜索"];
    [_searchController.searchBar setBarTintColor:[UIColor colorWithRed:0.95f green:0.95f blue:0.95f alpha:1.00f]];
    //设置搜索logo
    [_searchController.searchBar setImage:[UIImage imageNamed:@"last.png"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    [_searchController.searchBar sizeToFit];
    [_searchController.searchBar setDelegate:self];
    [_searchController.searchBar.layer setBorderWidth:0.5f];
    [_searchController.searchBar.layer setBorderColor:[UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0].CGColor];
    [_tableView setTableHeaderView:_searchController.searchBar];

    _searchVC.searchVC = _searchController;
    __weak UISearchController *searchVC = _searchController;

    _searchVC.backBlock = ^(){
        [searchVC dismissViewControllerAnimated:YES completion:nil];
        searchVC.searchBar.text = @"";
    };
}

- (void) navRightButtonDown
{
    NSLog(@"---------------");
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"第%ld行",(long)indexPath.row];
    return cell;
}


#pragma mark - UISearchBarDelegate

- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.tabBarController.tabBar setHidden:YES];
}

- (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    //这里也可以不做取消操作,而是该用确认搜索的操作,使用.h中的代理把值传到搜索结果那里进行网络请求
    [self.tabBarController.tabBar setHidden:NO];
    NSLog(@"---------------Cancel");

}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"---------------%@",searchBar.text);

    if ([self.delegate respondsToSelector:@selector(searchMyInput:)]) {
        [self.delegate searchMyInput:searchBar.text];
    }
}

博主在这里用协议代理把输入内容传递到了结果页来进行操作,当然,也可以在当前页进行操作然后传到结果页进行展示,这里只是提供一种方式,并未限制别的写法。

结果页代码:

.h
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface SearchResultViewController : UIViewController <UISearchResultsUpdating,SearchInputtingDelegate>

@property(nonatomic,copy)void(^backBlock)(void);
@property(nonatomic,strong)UISearchController *searchVC;

@end


.m

#import "SearchResultViewController.h"

@interface SearchResultViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableView;
    UIView *view;
}
@end

@implementation SearchResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.automaticallyAdjustsScrollViewInsets = NO;




}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"第%ld条搜索数据",(long)indexPath.row];
    return cell;
}


- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}


#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchText = searchController.searchBar.text;
    NSLog(@"%@", searchText);


    if (searchController.searchBar.text.length >15) {
        searchController.searchBar.text = [searchText substringToIndex:15];
    }
}

#pragma mark - SearchInputtingDelegate
- (void)searchMyInput:(NSString *)inputStr
{
    NSLog(@"To Search My Inputthing");
    self.view.backgroundColor = [UIColor whiteColor];

    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height - 64)];
    _tableView.alpha = 0;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];

    view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 64)];
    view.backgroundColor = [UIColor orangeColor];
    view.alpha = 0;
    [self.view addSubview:view];
    [self creatBackBtn];


    [UIView animateWithDuration:1 animations:^{
        self.searchVC.searchBar.hidden = YES;
        _tableView.alpha = 1;
        view.alpha = 1;

    }];



}

- (void)creatBackBtn
{
    UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeSystem];
    backbtn.frame = CGRectMake(0, 20, 60, 44);
    [backbtn setTitle:@"返回" forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:backbtn];


}

- (void)backAction
{
    self.searchVC.searchBar.hidden = NO;
    [_tableView removeFromSuperview];
    [view removeFromSuperview];
    self.backBlock();
}

结果页展示后会看到nav依然为搜索框,点击取消后回来搜索前页面,这个个人感觉其实也没什么,如果觉得用户体验不好,那就隐藏掉搜索框好了,再定义一个nav,放一个按钮用于回到搜索前的界面,以上功能都已实现,代码如上,Demo下载地址:
github.com/codeliu6572…