iOS 利用collectionView代码布局实现搜索历史,UISearchBar搜索框

2024-01-17 07:10

本文主要是介绍iOS 利用collectionView代码布局实现搜索历史,UISearchBar搜索框,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

效果如下:
搜索功能
控制器代码如下:

#import "HBSearchHeaderTitleView.h"
#import "HBSearchHistoryWordCell.h"
#import "HBSearchHotWordCell.h"
#import "UICollectionViewLeftAlignedLayout.h"
@interface HBSearchViewController ()<UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic ,strong)UIView *navView;
@property (nonatomic ,strong)UISearchBar *searchBar;
@property (nonatomic ,strong)UIButton *cancelBtn;//取消按钮
@property (nonatomic ,strong)UICollectionView *collectionView;
@property (nonatomic ,strong)NSMutableArray *historyWordsAry;//历史记录
@property (nonatomic ,strong)NSArray *hotWordsAry;//热搜
@end@implementation HBSearchViewController-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];self.navigationController.navigationBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{[super viewWillDisappear:animated];self.navigationController.navigationBar.hidden = NO;//保存历史到本地if ([NSKeyedArchiver archiveRootObject:_historyWordsAry toFile:kSearchHistoryCachePath]) {NSLog(@"缓存搜索历史成功!!");}
}
//-(NSArray *)historyWordsAry{
//    if (!_historyWordsAry) {
//        _historyWordsAry = @[@"衣服",@"衣服",@"衣意思是酸辣粉",@"衣服",@"衣服"];
//    }
//    return _historyWordsAry;
//}
-(NSArray *)hotWordsAry{if (!_hotWordsAry) {_hotWordsAry = @[@"裤子",@"衣服",@"衣意思是酸辣粉衣意思是酸辣粉酸辣粉",@"衣服",@"衣意思是酸辣粉",@"衣服",@"衣意思是酸辣粉",@"衣服",@"衣意思是酸辣粉",@"衣服",@"衣意思是酸辣粉",@"衣服",@"衣意思是酸辣粉",@"衣服",@"衣意思是酸辣粉",@"衣服",@"衣意思是酸辣粉",@"衣服衣",@"衣意思是酸辣粉",@"衣服"];}return _hotWordsAry;
}
#pragma mark ==========点击取消按钮==========
-(void)clickCancelBtn:(UIButton *)btn{[self.searchBar resignFirstResponder];[self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.self.view.backgroundColor = [UIColor whiteColor];self.title = @"搜索";self.historyWordsAry = [NSMutableArray array];_historyWordsAry = [[NSKeyedUnarchiver unarchiveObjectWithFile:kSearchHistoryCachePath] mutableCopy];if (_historyWordsAry == nil) _historyWordsAry = [NSMutableArray arrayWithCapacity:1];//添加子视图[self addSubViewUI];
}
#pragma mark ==========添加子视图==========
-(void)addSubViewUI{[self.view addSubview:self.navView];[self.navView mas_makeConstraints:^(MASConstraintMaker *make) {make.top.left.right.equalTo(self.view);make.height.mas_equalTo(NAVIBAR_HEIGHT);}];CGFloat btnWidth = 40;CGFloat searchHeight = 40;[self.navView addSubview:self.searchBar];[self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {make.bottom.equalTo(self.navView).offset(-10);make.left.equalTo(self.navView).offset(15);make.right.equalTo(self.navView).offset(-10-15-btnWidth);make.height.mas_equalTo(searchHeight);}];[self.navView addSubview:self.cancelBtn];[self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {make.centerY.equalTo(self.searchBar);make.left.equalTo(self.searchBar.mas_right).offset(10);make.size.mas_equalTo(CGSizeMake(btnWidth, btnWidth));}];[self.view addSubview:self.collectionView];[self.collectionView reloadData];[self.searchBar becomeFirstResponder];
}
#pragma mark - UICollectionView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{if (kind == UICollectionElementKindSectionHeader) {HBSearchHeaderTitleView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CELLID([HBSearchHeaderTitleView class]) forIndexPath:indexPath];WEAKSELF;if (indexPath.section == 0) {
//            header.delBtn.hidden = NO;header.titleLabel.text = @"历史搜索";header.backgroundColor = [UIColor whiteColor];
//            [header.delBtn bk_addEventHandler:^(id sender) {
//
//                weakSelf.isDelHistory = !weakSelf.isDelHistory;
//                [weakSelf.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
//            } forControlEvents:UIControlEventTouchUpInside];} else {header.titleLabel.text = @"大家都在搜";
//            header.delBtn.hidden = YES;}return header;}return nil;
}
#pragma mark-表头尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{return CGSizeMake(SCREEN_WIDTH, 40);
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{if (section == 0) {return self.historyWordsAry.count;}return self.hotWordsAry.count;
}- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{return 2;
}- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{if (indexPath.section == 0) {WEAKSELF;HBSearchHistoryWordCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELLID([HBSearchHistoryWordCell class]) forIndexPath:indexPath];
//        cell.delBtn.hidden = !self.isDelHistory;NSString *text = self.historyWordsAry[indexPath.row];cell.titleLabel.text = text;
//        [cell.delBtn bk_addEventHandler:^(id sender) {
//
//            [weakSelf.historyWordsAry removeObject:text];
//            [weakSelf.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
//        } forControlEvents:UIControlEventTouchUpInside];return cell;} else {HBSearchHotWordCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELLID([HBSearchHotWordCell class]) forIndexPath:indexPath];cell.titleLabel.text = self.hotWordsAry[indexPath.row];return cell;}
}- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{NSString *searchText = @"";if (indexPath.section == 0) {//热词searchText = self.historyWordsAry[indexPath.row];}else if (indexPath.section == 1) {//热词searchText = self.hotWordsAry[indexPath.row];}_searchBar.text = searchText;[self searchGoods];
}
- (void)searchGoods{NSString *search = _searchBar.text;if (search.length == 0) {
//        [NSObject showToastWithText:];//@"请输入搜索的商品名称"return;}//隐藏键盘[self.view endEditing:YES];//    self.searchText = search.removeAllSpace;if (![_historyWordsAry containsObject:search]) [_historyWordsAry addObject:search];//    kDefineWeakSelf;
//    [YXShoppingService searchGoodsWithName:_searchText pageNum:_page sort:_sort order:_order success:^(YXShoppingSearchGoodsListModel *obj) {
//
//        weakSelf.listModel = obj;
//        weakSelf.collectionView.hidden = YES;
//        weakSelf.tableView.hidden = NO;
//
//        if (obj.list.count == 0) {
//            //没数据
//            weakSelf.isShowEmptyView = YES;
//            weakSelf.tintImgName = @"yx_yhq_wu-ss";
//            weakSelf.tintStr = @"还没有数据哦~~";
//        }
//
//        [weakSelf.tableView reloadData];
//    } fail:^(NSString *str) {
//
//        weakSelf.collectionView.hidden = YES;
//        weakSelf.tableView.hidden = NO;
//        //没数据
//        weakSelf.isShowEmptyView = YES;
//        weakSelf.tintStr = str; //@"网络请求失败,请重试";
//        [weakSelf.tableView reloadData];
//    }];
}- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{if (indexPath.section == 0) {NSString *text = self.historyWordsAry[indexPath.row];return [HBSearchHistoryWordCell getSizeWithText:text];} else {NSString *text = self.hotWordsAry[indexPath.row];return [HBSearchHistoryWordCell getSizeWithText:text];}
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {return UIEdgeInsetsMake(0, 15, 0, 0);
}
#pragma mark - UISearchBar
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{[self searchGoods];
}
#pragma mark ==========getter==========
-(UIView *)navView{if (!_navView) {_navView = ({UIView *view = [UIView new];//初始化控件view.backgroundColor = [UIColor whiteColor];view ;}) ;}return _navView ;
}
-(UISearchBar *)searchBar{if (!_searchBar) {_searchBar = ({UISearchBar *seBar = [[UISearchBar alloc]init];seBar.delegate = self;if (@available(iOS 13, *)) {seBar.searchTextField.font = [UIFont systemFontOfSize:13];} else {UITextField *textfield = [seBar valueForKey:@"_searchField"];textfield.font = [UIFont systemFontOfSize:13];}//默认白色搜索框,多出的背景为灰色;UIBarStyleDefault 默认 UIBarStyleBlack背景为黑色seBar.barStyle = UIBarStyleDefault;//设置搜索框整体的风格为不显示背景,默认为Prominent显示seBar.searchBarStyle = UISearchBarStyleDefault;[seBar setBackgroundImage:[UIImage new]];[seBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"yx_search_field_bg"] forState:UIControlStateNormal];seBar.placeholder = @"复制标题,搜隐藏优惠券拿返利";seBar;});}return _searchBar;
}
-(UIButton *)cancelBtn{if (!_cancelBtn) {_cancelBtn = ({//创建按钮UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];//设置标题[button setTitle:@"取消" forState:UIControlStateNormal];//设置字体大小button.titleLabel.font = [UIFont systemFontOfSize:14];//设置title颜色[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];//添加点击事件[button addTarget:self action:@selector(clickCancelBtn:) forControlEvents:UIControlEventTouchUpInside];button;});}return _cancelBtn;
}
#pragma mark -Getter
-(UICollectionView *)collectionView{if (!_collectionView) {//创建 layout(此处创建的是流水布局)UICollectionViewLeftAlignedLayout *flowLayout = [[UICollectionViewLeftAlignedLayout alloc] init];flowLayout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 30);flowLayout.minimumLineSpacing = 10;flowLayout.minimumInteritemSpacing = 10;_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, NAVIBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-NAVIBAR_HEIGHT) collectionViewLayout:flowLayout];_collectionView.backgroundColor = [UIColor whiteColor] ;_collectionView.delegate = self ;_collectionView.dataSource = self ;_collectionView.showsVerticalScrollIndicator = NO;_collectionView.showsHorizontalScrollIndicator = NO;//注册 item[_collectionView registerClass:[HBSearchHeaderTitleView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CELLID([HBSearchHeaderTitleView class])];[_collectionView registerClass:[HBSearchHistoryWordCell class] forCellWithReuseIdentifier:CELLID([HBSearchHistoryWordCell class])];[_collectionView registerClass:[HBSearchHotWordCell class] forCellWithReuseIdentifier:CELLID([HBSearchHotWordCell class])];}return _collectionView ;
}
@end

demo地址:HBSearchNavDemo

END.

这篇关于iOS 利用collectionView代码布局实现搜索历史,UISearchBar搜索框的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/615227

相关文章

SpringBoot3实现Gzip压缩优化的技术指南

《SpringBoot3实现Gzip压缩优化的技术指南》随着Web应用的用户量和数据量增加,网络带宽和页面加载速度逐渐成为瓶颈,为了减少数据传输量,提高用户体验,我们可以使用Gzip压缩HTTP响应,... 目录1、简述2、配置2.1 添加依赖2.2 配置 Gzip 压缩3、服务端应用4、前端应用4.1 N

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

MySQL双主搭建+keepalived高可用的实现

《MySQL双主搭建+keepalived高可用的实现》本文主要介绍了MySQL双主搭建+keepalived高可用的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、测试环境准备二、主从搭建1.创建复制用户2.创建复制关系3.开启复制,确认复制是否成功4.同

Java实现文件图片的预览和下载功能

《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... Java实现文件(图片)的预览和下载 @ApiOperation("访问文件") @GetMapping("