您的位置:首页 > 产品设计 > UI/UE

IOS-搜索功能实现, UIsearchController的使用

2015-02-09 15:47 519 查看
开发中,搜索功能使用的频率自然不言而喻, 本文主要讲一些常用的

1.先创建一个搜索框(比较简单的一个搜索框, 系统自带的)

- (void)viewDidLoad {

[super
viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

self.view.backgroundColor = [UIColor
whiteColor];

UISearchBar *myBar = [[UISearchBar
alloc]
init];
myBar.frame =
CGRectMake(0 ,
65, self.view.frame.size.width,
30);
[self.view
addSubview:myBar];

//
显示cancel

myBar.showsCancelButton =
YES;
}

看一下效果:



但是系统的搜索框并不是很美观,可以用图片设计,IOS7之前可以用
  myBar.backgroundImage=[UIImage resizedImage:@"searchbar_background"];


但是在IOS7之后看不出效果,我们可以给UIimage条件延展,

@implementation UIImage (Extension) // 根据图片名自动加载适配IOS6和iOS7的图片

+ (UIImage *)imageWithName:(NSString *)name { UIImage *image = nil; if (iOS7) { // 处理iOS7的情况 NSString *newName = [name stringByAppendingString:@"_os7"]; image = [UIImage imageNamed:newName]; } if (image == nil) { image = [UIImage imageNamed:name]; } return image; }
// 根据图片名返回一张能自由拉伸的图片


+ (UIImage *)resizedImage:(NSString *)name { UIImage *image = [UIImage imageWithName:name]; return [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5]; }
如果还是不满意的话就只有自己定义一个搜索栏了, 关于自己封装搜索框,这里就不作说明了下面说一下UISearchController,在IOS8之前都是用UISearchDisplayController, 但是IOS8之后就用UISearchController, UISearchController用起来很方便, 它本身就带有searchBar, 而且自动会模态推到导航栏,下面看一下具体的使用,用UIsearchController实现一个搜索功能由于这个实现功能是点击一个searchbar 之后触发另一个方法A, 方法A实现的创建UIsearchController, 因此,大家可以根据实际情况操作
首先在.h里@interface SearchViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>// searchCollectionView@property (nonatomic, retain) UICollectionView *searchCollectionView;// mySearchController@property (nonatomic, retain) UISearchController *mySearchController;// 搜索按钮@property (nonatomic, retain) UIButton *searchButton;
// 存放所有数据的数组@property (nonatomic, retain) NSMutableArray *allDataArray;// 存放搜索出结果的数组@property (nonatomic, retain) NSMutableArray *searchResultDataArray;// 搜索控制器@property (nonatomic, retain) UISearchController *searchController;// 搜索使用的表示图控制器@property (nonatomic, retain) UITableViewController *searchTVC;// searchBar@property (nonatomic, retain) UISearchBar *bar;// 搜索框输入的东西@property (nonatomic, copy) NSString *inputText;
接下来.m里1. 创建一个searchBar(其实这个searchBar没有说明大用处)
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor brownColor]; // 创建searchBar self.bar=[[UISearchBar alloc]init]; self.navigationItem.title = @"搜索漫画"; //设置bar的frame self.bar.frame=CGRectMake(0, 65, 300, 35); [self.view addSubview:self.bar]; self.bar.placeholder = @"漫画名/作者/类型"; // 设置键盘类型 self.bar.keyboardType = UIKeyboardTypeNamePhonePad; // searchBar 代理,记得签协议 self.bar.delegate = self;}
2. 触发方法,创建searchController// searchBar的代理方法,当searchBar的textField开始编辑的时候调用,包含空- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{ // 创建出搜索使用的表示图控制器 self.searchTVC = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain]; _searchTVC.tableView.dataSource = self; _searchTVC.tableView.delegate = self; // 使用表示图控制器创建出搜索控制器 self.searchController = [[UISearchController alloc] initWithSearchResultsController:_searchTVC]; // 搜索框检测代理 //(这个需要遵守的协议是 <UISearchResultsUpdating> ,这个协议中只有一个方法,当搜索框中的值发生变化的时候,代理方法就会被调用) _searchController.searchResultsUpdater = self; _searchController.delegate = self; _searchController.searchBar.placeholder = @"漫画名/作者/类型"; // _searchController.searchBar.delegate = self; [self presentViewController:_searchController animated:YES completion:^{ // 当模态推出这个searchController的时候,需要把之前的searchBar隐藏,如果希望搜索的时候看不到热门搜索什么的,可以把这个页面给隐藏 self.bar.hidden = YES; self.view.hidden = YES; }];}
3.监听输入的关键字, 把输入的关键字,传到接口处去请求数据#pragma mark - UISearchResultsUpdating Method#pragma mark 监听者搜索框中的值的变化- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{ // 1. 获取输入的值 self.inputText = searchController.searchBar.text; [self afn1];}
4. 请求数据并解析(我这里用的时AFN请求, 其他方法都可以,随意)// afnq请求数据(搜索数据)-(void)afn1{ AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager]; NSLog(@"%d", netWorkManager.isReachable); NSString *url_string = [NSString stringWithFormat:@"http://pappappap", self.inputText]; NSString *url = [url_string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"nnnnnn%@", url);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { [netWorkManager stopMonitoring]; NSLog(@"kkk object = %@", responseObject); NSMutableDictionary *dic = [NSMutableDictionary dictionary]; dic = responseObject; self.searchResultDataArray = [NSMutableArray array]; NSMutableDictionary *dic1 = [dic objectForKey:@"info"]; NSMutableDictionary *dic2 = [dic1 objectForKey:@"data"]; NSMutableArray *array = [dic2 objectForKey:@"items"]; for (NSMutableDictionary *dic in array) { Comicslist *comics = [[Comicslist alloc] init]; comics.bigbook_id = [NSString stringWithFormat:@"%@", [dic objectForKey:@"id"]]; comics.bigbook_name = [dic objectForKey:@"name"]; comics.bigbook_author = [dic objectForKey:@"author"]; comics.coverurl = [dic objectForKey:@"coverurl"]; // NSString *key = [dic objectForKey:@"key_name"]; // comics.key_name = [NSString stringWithFormat:@"%@%@",comics.bigbook_name, comics.bigbook_author]; [self.searchResultDataArray addObject:comics]; } [_searchTVC.tableView reloadData]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"失败 %@", error); }]; }

5.设置显示搜索结果的tableView, 即self.searchTVC的tableView// 设置搜索tableView section个数- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return 1;}
// 设置搜索tableView cell个数- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ if (_searchResultDataArray.count == 0) { NSLog(@"33333"); return 1; } return _searchResultDataArray.count;}
// 设置搜索tableView的cell- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *cellIdentifier = @"indenfy"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } if (self.searchResultDataArray.count != 0) { Comicslist *comics = [self.searchResultDataArray objectAtIndex:indexPath.row]; cell.textLabel.text = comics.bigbook_name; NSString *str = comics.coverurl; NSURL *url = [NSURL URLWithString:str]; UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]]; cell.imageView.image = image; }else{ cell.textLabel.text = @"没有查找的内容"; cell.imageView.image = nil; } return cell;}

// 设置cell高度 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 100;}
6. 设置搜索tableView 点击进入搜索结果- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ // 跳转操作}
7.细节处理(1)当搜索页面消失的时候,让原先的搜索bar和View显示-(void)didDismissSearchController:(UISearchController *)searchController{ self.bar.hidden = NO; self.view.hidden = NO;}
(2)当View将要出现的时候, view显示- (void)viewWillAppear:(BOOL)animated{ self.view.hidden = NO;
}(3) 取消按钮触发方法, 点击取消后,self.bar和self.view显示出来-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{ self.bar.hidden = NO; self.view.hidden = NO;}
哈哈,激动人心的时刻,看一下运行的结果:1.进入搜索界面



2.点击触发创建searchController



3.进行搜索



4.点击取消按钮后回原来的界面

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: