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

相关文章

Spring IOC的三种实现方式详解

《SpringIOC的三种实现方式详解》:本文主要介绍SpringIOC的三种实现方式,在Spring框架中,IOC通过依赖注入来实现,而依赖注入主要有三种实现方式,构造器注入、Setter注入... 目录1. 构造器注入(Cons编程tructor Injection)2. Setter注入(Setter

Android kotlin语言实现删除文件的解决方案

《Androidkotlin语言实现删除文件的解决方案》:本文主要介绍Androidkotlin语言实现删除文件的解决方案,在项目开发过程中,尤其是需要跨平台协作的项目,那么删除用户指定的文件的... 目录一、前言二、适用环境三、模板内容1.权限申请2.Activity中的模板一、前言在项目开发过程中,尤

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC

Python实现文件下载、Cookie以及重定向的方法代码

《Python实现文件下载、Cookie以及重定向的方法代码》本文主要介绍了如何使用Python的requests模块进行网络请求操作,涵盖了从文件下载、Cookie处理到重定向与历史请求等多个方面,... 目录前言一、下载网络文件(一)基本步骤(二)分段下载大文件(三)常见问题二、requests模块处理

vscode保存代码时自动eslint格式化图文教程

《vscode保存代码时自动eslint格式化图文教程》:本文主要介绍vscode保存代码时自动eslint格式化的相关资料,包括打开设置文件并复制特定内容,文中通过代码介绍的非常详细,需要的朋友... 目录1、点击设置2、选择远程--->点击右上角打开设置3、会弹出settings.json文件,将以下内

Java中使用Java Mail实现邮件服务功能示例

《Java中使用JavaMail实现邮件服务功能示例》:本文主要介绍Java中使用JavaMail实现邮件服务功能的相关资料,文章还提供了一个发送邮件的示例代码,包括创建参数类、邮件类和执行结... 目录前言一、历史背景二编程、pom依赖三、API说明(一)Session (会话)(二)Message编程客

Java中List转Map的几种具体实现方式和特点

《Java中List转Map的几种具体实现方式和特点》:本文主要介绍几种常用的List转Map的方式,包括使用for循环遍历、Java8StreamAPI、ApacheCommonsCollect... 目录前言1、使用for循环遍历:2、Java8 Stream API:3、Apache Commons

C#提取PDF表单数据的实现流程

《C#提取PDF表单数据的实现流程》PDF表单是一种常见的数据收集工具,广泛应用于调查问卷、业务合同等场景,凭借出色的跨平台兼容性和标准化特点,PDF表单在各行各业中得到了广泛应用,本文将探讨如何使用... 目录引言使用工具C# 提取多个PDF表单域的数据C# 提取特定PDF表单域的数据引言PDF表单是一

使用Python实现高效的端口扫描器

《使用Python实现高效的端口扫描器》在网络安全领域,端口扫描是一项基本而重要的技能,通过端口扫描,可以发现目标主机上开放的服务和端口,这对于安全评估、渗透测试等有着不可忽视的作用,本文将介绍如何使... 目录1. 端口扫描的基本原理2. 使用python实现端口扫描2.1 安装必要的库2.2 编写端口扫

PyCharm接入DeepSeek实现AI编程的操作流程

《PyCharm接入DeepSeek实现AI编程的操作流程》DeepSeek是一家专注于人工智能技术研发的公司,致力于开发高性能、低成本的AI模型,接下来,我们把DeepSeek接入到PyCharm中... 目录引言效果演示创建API key在PyCharm中下载Continue插件配置Continue引言