iOS程序猿iOS、swift技术交流!iOS技术点

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

2016-06-24  本文已影响7073人  Xcode8

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

上一篇下一篇

猜你喜欢

热点阅读