UISearchController是蘋果提供的一種搜索的效果,從iOS8.0之后出來(lái)的遥皂。
效果圖:
實(shí)現(xiàn)思路
這種看著是一個(gè)頁(yè)面的實(shí)現(xiàn)搜索效果。其實(shí)是二個(gè)類似的頁(yè)面的布局的效果。點(diǎn)擊搜索欄之后,到了另外一個(gè)界面锭碳,實(shí)現(xiàn)搜索效果。
一勿璃、核心代碼實(shí)現(xiàn)
遵守的代理方法
<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchResultsUpdating,UISearchControllerDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;//collectionView視圖的布局
@property (nonatomic,strong)NSMutableArray *dataArray;//全部數(shù)據(jù)數(shù)組
@property (nonatomic,strong)NSMutableArray *searchArray;//搜索結(jié)果數(shù)組
@property (nonatomic,strong)UISearchController *searchC;//搜索控制器
@property (nonatomic,strong)SearchCollectionController *searchCollectionC;//搜索結(jié)果控制器
//添加搜索欄
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;
//搜索結(jié)果的代理設(shè)置
self.searchC.searchResultsUpdater = self;
核心的代碼
#pragma mark---搜索代理方法擒抛,搜索框獲得第一響應(yīng)或內(nèi)容變化時(shí)觸發(fā)
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
// 得到搜索框的文字
NSString* str = searchController.searchBar.text;
NSLog(@"%@",str);
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"imageName CONTAINS[c]%@ ",str];
//清空搜索數(shù)組
[self.searchArray removeAllObjects];
self.searchArray = [NSMutableArray arrayWithArray:[self.dataArray filteredArrayUsingPredicate:namePredicate]];
//此句代碼跳轉(zhuǎn)到搜索控制器的結(jié)果
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的展示數(shù)據(jù)內(nèi)容a
*/
@property(nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *dataArray;//全部數(shù)據(jù)數(shù)組
@property (nonatomic,strong)NSMutableArray *searchArray;//搜索結(jié)果數(shù)組
@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 ];
//代碼設(shè)置的問題-----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";
//搜索結(jié)果不變灰
self.searchC.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = YES;
//便利初始化創(chuàng)建數(shù)據(jù)
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];
//把全部人存到數(shù)組當(dāng)中去
[self.dataArray addObject:model];
}
[self setOneCollectionView];
}
/**
* main的collectionview
*/
- (void)setOneCollectionView{
//創(chuàng)建集合視圖
self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
self.flowLayout.minimumInteritemSpacing = 5;
self.flowLayout.minimumLineSpacing = 33;
self.flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);//分區(qū)內(nèi)邊距
//itemsize大小我們?cè)O(shè)置為一行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);
//創(chuàng)建collectionView對(duì)象,并賦值布局
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 54, kwidth, kheight) collectionViewLayout:self.flowLayout];
//設(shè)置數(shù)據(jù)源和代理
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
self.collectionView.bounces = NO;
self.collectionView.backgroundColor = [UIColor whiteColor];
//注冊(cè)單元格
[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{
//執(zhí)行完以下語(yǔ)句后調(diào)用 MyCollectionViewCell.m 的 initWithFrame方法
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
//設(shè)置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---搜索代理方法歧沪,搜索框獲得第一響應(yīng)或內(nèi)容變化時(shí)觸發(fā)
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
//得到搜索框的文字
NSString* str = searchController.searchBar.text;
NSLog(@"%@",str);
//清空搜索數(shù)組
[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) {
//添加內(nèi)部控件
//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
/**
* 模型賦值是遇到?jīng)]有定義的特例處理
*/
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
- (void)setNilValueForKey:(NSString *)key{
}
@end
搜索結(jié)果的控制器
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];
}
//有新值的變化歹撒,調(diào)用這個(gè)方法
- (void)setSearchResults:(NSMutableArray *)searchResults
{
_searchResults = searchResults;
[self.collectionView1 reloadData];
}
/**
* main的collectionview
*/
- (void)setOneCollectionView{
//創(chuàng)建集合視圖
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.minimumInteritemSpacing = 5;
flowLayout.minimumLineSpacing = 33;
flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);//分區(qū)內(nèi)邊距
//itemsize大小我們?cè)O(shè)置為一行4列
CGFloat totalWidth = kwidth;
CGFloat itemWidth = (totalWidth-3*5-2*5)/4.0;
CGFloat itemHeght = 1.0*itemWidth;
//注意:item的寬高必須要提前算好
flowLayout.itemSize = CGSizeMake(itemWidth, itemHeght);
//創(chuàng)建collectionView對(duì)象,并賦值布局
self.collectionView1 = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, kwidth, kheight) collectionViewLayout:flowLayout];
//設(shè)置數(shù)據(jù)源和代理
self.collectionView1.dataSource = self;
self.collectionView1.delegate = self;
self.collectionView1.bounces = NO;
self.collectionView1.backgroundColor = [UIColor whiteColor];
//注冊(cè)單元格
[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{
//執(zhí)行完以下語(yǔ)句后調(diào)用 MyCollectionViewCell.m 的 initWithFrame方法
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
//設(shè)置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
點(diǎn)擊跳轉(zhuǎn)的詳情頁(yè)面
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
代碼到此結(jié)束 诊胞,希望大家批評(píng)指正暖夭,謝謝大家。大家感覺寫的還可以的話記得給個(gè)star
撵孤。(嘻嘻哈哈)迈着,謝謝大家
githup網(wǎng)址:https://github.com/jinweicheng/UISearchController