UISearchController的搜索栏的实现(带有跳转页面)


UISearchController是苹果提供的一种搜索的效果,从iOS8.0之后出来的。
效果图:

2016-06-24_11-35-43.gif

实现思路

这种看着是一个页面的实现搜索效果。其实是二个类似的页面的布局的效果。点击搜索栏之后,到了另外一个界面,实现搜索效果。

一、核心代码实现

遵守的代理方法
<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchResultsUpdating,UISearchControllerDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;//collectionView视图的布局
@property (nonatomic,strong)NSMutableArray *dataArray;//全部数据数组
@property (nonatomic,strong)NSMutableArray *searchArray;//搜索结果数组
@property (nonatomic,strong)UISearchController *searchC;//搜索控制器
@property (nonatomic,strong)SearchCollectionController *searchCollectionC;//搜索结果控制器
//添加搜索栏
    self.searchCollectionC = [[SearchCollectionController alloc] init];
    self.searchCollectionC.view.frame = CGRectMake(0, 64, kwidth, 1.5*kheight);
    self.searchC = [[UISearchController alloc] initWithSearchResultsController:self.searchCollectionC ];
    self.searchC.delegate = self;
//搜索结果的代理设置
    self.searchC.searchResultsUpdater = self;
核心的代码
#pragma mark---搜索代理方法,搜索框获得第一响应或内容变化时触发
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    //    得到搜索框的文字
    NSString* str = searchController.searchBar.text;
    NSLog(@"%@",str);
    NSPredicate *namePredicate = [NSPredicate         predicateWithFormat:@"imageName CONTAINS[c]%@ ",str];
    //清空搜索数组
    [self.searchArray removeAllObjects];
    self.searchArray =  [NSMutableArray arrayWithArray:[self.dataArray filteredArrayUsingPredicate:namePredicate]];
//此句代码跳转到搜索控制器的结果
    self.searchCollectionC.searchResults = self.searchArray;
}

二、完整代码

AppDelegate.h

#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

AppDelegate.m

#import "AppDelegate.h"
#import "CollectionController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window.frame = [UIScreen mainScreen].bounds;
    self.window.backgroundColor = [UIColor whiteColor];
    CollectionController *cc = [[CollectionController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cc];
    self.window.rootViewController = nav;
    [self.window  makeKeyWindow];
    [self.window makeKeyAndVisible];
    return YES;
}
@end


CollectionController.h

#import <UIKit/UIKit.h>
@interface CollectionController : UIViewController
@end

CollectionController.m

#import "CollectionController.h"
#import "CollectionViewCell.h"
#import "CollectionModel.h"
#import "DetailViewController.h"
#import "SearchCollectionController.h"
static NSString * const reuseIdentifier = @"myCell";
@interface CollectionController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchResultsUpdating,UISearchControllerDelegate>
/**
 *  存放tableViewCell的展示数据内容a
 */
@property(nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *dataArray;//全部数据数组
@property (nonatomic,strong)NSMutableArray *searchArray;//搜索结果数组
@property (nonatomic,strong)UISearchController *searchC;//搜索框
@property (nonatomic,strong)SearchCollectionController *searchCollectionC;
@property (nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@end
@implementation CollectionController
//懒加载
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
-(NSMutableArray *)searchArray
{
    if (!_searchArray) {
        _searchArray = [[NSMutableArray alloc]init];
    }
    return _searchArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //此代码的问题解决方案-----888666
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"search";
    //添加搜索栏
    self.searchCollectionC = [[SearchCollectionController alloc] init];
    self.searchCollectionC.view.frame = CGRectMake(0, 64, kwidth, 1.5*kheight);
    self.searchC = [[UISearchController alloc] initWithSearchResultsController:self.searchCollectionC ];
    //代码设置的问题-----888666
   self.searchC.searchBar.frame = CGRectMake(self.searchC.searchBar.frame.origin.x, self.searchC.searchBar.frame.origin.y, kwidth,44);
    [self.searchCollectionC.view addSubview:self.searchC.searchBar];
    self.searchC.delegate = self;
    //2016-06-17添加
    self.definesPresentationContext = YES;
    [self.searchC.searchBar sizeToFit];
    [self.view addSubview:self.searchC.searchBar];
//    [self.collectionView addSubview:self.searchC.searchBar];
    //更新代理
    self.searchC.searchResultsUpdater = self;
    self.searchC.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    self.searchC.searchBar.barTintColor = [UIColor redColor];
    self.searchC.searchBar.placeholder = @"qingshuru";
    //搜索结果不变灰
    self.searchC.dimsBackgroundDuringPresentation = NO;
    self.definesPresentationContext = YES;
    //便利初始化创建数据
    NSArray *nameArray = [NSArray arrayWithObjects:@"a",@"b",@"c",@"z菲",@"wbe",@"ABe",@"aBS",@"wang@12.com", @"wan@126.cn",@"cheng",@"tian",@"jia",@"zai",@"程",@"为",@"逛",@"哈哈",@"kkk",@"yyy",nil];
    
    for (int i = 0; i < nameArray.count; i++) {
        CollectionModel *model = [[CollectionModel alloc] init];
        model.imageName = nameArray[i];
        //把全部人存到数组当中去
        [self.dataArray addObject:model];
    }
    [self setOneCollectionView];
    
}
/**
 *  main的collectionview
 */
- (void)setOneCollectionView{
    
    //创建集合视图
    self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
    self.flowLayout.minimumInteritemSpacing = 5;
    self.flowLayout.minimumLineSpacing = 33;
    self.flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);//分区内边距
    //itemsize大小我们设置为一行4列
    CGFloat totalWidth = kwidth;
    CGFloat itemWidth = (totalWidth-3*5-2*5)/4.0;
    CGFloat itemHeght = 1.0*itemWidth;
    //注意:item的宽高必须要提前算好
    self.flowLayout.itemSize = CGSizeMake(itemWidth, itemHeght);
    //创建collectionView对象,并赋值布局
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 54, kwidth, kheight) collectionViewLayout:self.flowLayout];
    //设置数据源和代理
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.bounces = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
       //注册单元格
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    //添加
    [self.view addSubview:self.collectionView];
    
}
#pragma mark--UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //执行完以下语句后调用   MyCollectionViewCell.m  的 initWithFrame方法
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    //设置cell
    cell.imageView.image = [UIImage imageNamed:@"1.jpg"];
    CollectionModel *model = [[CollectionModel alloc] init];
    
    model = self.dataArray[indexPath.item];
    cell.lable.text = [NSString stringWithFormat:@"%@",model.imageName];
    return cell;
}

#pragma mark--UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld %ld",indexPath.section,indexPath.item);
    DetailViewController *detail = [[DetailViewController alloc] init] ;
    CollectionModel *model = [[CollectionModel alloc] init];
    model = self.dataArray[indexPath.item];
    detail.name = model.imageName;
    [self.navigationController pushViewController:detail animated:YES];
}

#pragma mark---搜索代理方法,搜索框获得第一响应或内容变化时触发
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    //得到搜索框的文字
    NSString* str = searchController.searchBar.text;
    NSLog(@"%@",str);
    //清空搜索数组
    [self.searchArray removeAllObjects];
    self.searchArray =  [NSMutableArray arrayWithArray:[self.dataArray filteredArrayUsingPredicate:namePredicate]];
    self.searchCollectionC.searchResults = self.searchArray;
    for (CollectionModel *model in self.searchArray) {
        NSLog(@"%@",model.imageName);
    }
}
@end

CollectionViewCell.h

#import <UIKit/UIKit.h>
@class CollectionModel;
@interface CollectionViewCell : UICollectionViewCell
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UILabel *lable;
@property(nonatomic,strong)CollectionModel *collectionModel;
@end

CollectionViewCell.m

#import "CollectionViewCell.h"
#import "CollectionModel.h"
@implementation CollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //添加内部控件
        //imageview
        CGFloat totalWidth = self.frame.size.width;
        CGFloat totalHeight = self.frame.size.height;
        self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, totalWidth, totalWidth)];
        self.imageView.backgroundColor = [UIColor redColor];
        [self addSubview:self.imageView];
        //lable
        self.lable = [[UILabel alloc]initWithFrame:CGRectMake(0, totalHeight+5, totalWidth, 20)];
        self.lable.textAlignment = NSTextAlignmentCenter;
        self.lable.layer.borderWidth = 0.5f;
        self.lable.layer.borderColor = [[UIColor grayColor] CGColor];
        [self addSubview:self.lable];   
    }
    return self;
}
- (void)setCollectionModel:(CollectionModel *)collectionModel{
    self.lable.text = collectionModel.imageName;
}
@end

CollectionModel.h

#import <Foundation/Foundation.h>
@interface CollectionModel : NSObject
@property(nonatomic,copy)NSString *image;
@property(nonatomic,copy)NSString *imageName;
@end

CollectionModel.m

#import "CollectionModel.h"
@implementation CollectionModel
/**
 *  模型赋值是遇到没有定义的特例处理
 */
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
    
}
- (void)setNilValueForKey:(NSString *)key{
    
}
@end

搜索结果的控制器
SearchCollectionController.h

#import <UIKit/UIKit.h>
@interface SearchCollectionController : UIViewController
@property (nonatomic, strong) NSMutableArray *searchResults;
@end

SearchCollectionController.m

#import "SearchCollectionController.h"
#import "CollectionViewCell.h"
#import "CollectionModel.h"
#import "DetailViewController.h"
static NSString * const reuseIdentifier = @"myCell";
@interface SearchCollectionController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>
@property(nonatomic,strong)UICollectionView *collectionView1;
@end
@implementation SearchCollectionController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"A8";
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.collectionView1 registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
      [self setOneCollectionView];    
}
//有新值的变化,调用这个方法
- (void)setSearchResults:(NSMutableArray *)searchResults
{
    _searchResults = searchResults;
    [self.collectionView1 reloadData];
    
}
/**
 *  main的collectionview
 */
- (void)setOneCollectionView{
    //创建集合视图
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 33;
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);//分区内边距
    //itemsize大小我们设置为一行4列
    CGFloat totalWidth = kwidth;
    CGFloat itemWidth = (totalWidth-3*5-2*5)/4.0;
    CGFloat itemHeght = 1.0*itemWidth;
    //注意:item的宽高必须要提前算好
    flowLayout.itemSize = CGSizeMake(itemWidth, itemHeght);
    //创建collectionView对象,并赋值布局
    self.collectionView1 = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, kwidth, kheight) collectionViewLayout:flowLayout];
    //设置数据源和代理
    self.collectionView1.dataSource = self;
    self.collectionView1.delegate = self;
    self.collectionView1.bounces = NO;
    self.collectionView1.backgroundColor = [UIColor whiteColor];
    //注册单元格
    [self.collectionView1 registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    //添加
    [self.view addSubview:self.collectionView1];
}

#pragma mark--UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.searchResults.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //执行完以下语句后调用   MyCollectionViewCell.m  的 initWithFrame方法
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    //设置cell
    cell.imageView.image = [UIImage imageNamed:@"1.jpg"];
    CollectionModel *model = [[CollectionModel alloc] init];
    model = self.searchResults[indexPath.item];
    cell.lable.text = [NSString stringWithFormat:@"%@",model.imageName];
    return cell;  
}

#pragma mark--UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld %ld",indexPath.section,indexPath.item);
    DetailViewController *detail = [[DetailViewController alloc] init] ;
    CollectionModel *model = [[CollectionModel alloc] init];
    model = self.searchResults[indexPath.item];
    detail.name = model.imageName;
    [self.presentingViewController.navigationController pushViewController:detail animated:YES];
}
@end

点击跳转的详情页面
DetailViewController.h

#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController
@property (nonatomic,strong)NSString *name;
@end

DetailViewController.m

#import "DetailViewController.h"
@interface DetailViewController ()
@end
@implementation DetailViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 100, 100, 100);
    [button setTitle:self.name forState:UIControlStateNormal];
    button.backgroundColor = [UIColor redColor];
    [self.view addSubview:button];
}
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden  = NO;
}
@end

代码到此结束 ,希望大家批评指正,谢谢大家。大家感觉写的还可以的话记得给个star。(嘻嘻哈哈),谢谢大家
githup网址:https://github.com/jinweicheng/UISearchController

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,657评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,662评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,143评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,732评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,837评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,036评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,126评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,868评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,315评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,641评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,773评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,859评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,584评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,676评论 2 351

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,856评论 25 707
  • 梦中花已开,回首梦不在。 再入梦中时,奈何花不再。
    创造快乐阅读 160评论 0 1
  • 写于重庆一家小破旅馆 (一) 牛吧青春 你牛什么 蟑螂爬来爬去 放肆的很 感到凉意 顺着脚升到心 明天走不走 (二...
    你是我的遗物阅读 147评论 0 1
  • 走过人生的四分之一,体会了人世的酸甜苦辣,亲情、爱情、友情,是人活在这世间不可或缺的东西,它们带给人喜悦与悲伤,渐...
    子棘阅读 364评论 3 2
  • 此刻,坐在咖啡陪你的靠窗位置。 一杯拿铁,一首歌。 蜷缩在自己的世界。 不止一次想念。却不知道该想念谁。多少时候,...
    尤宴阅读 379评论 0 2