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

相关文章

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

PyQt6/PySide6中QTableView类的实现

《PyQt6/PySide6中QTableView类的实现》本文主要介绍了PyQt6/PySide6中QTableView类的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学... 目录1. 基本概念2. 创建 QTableView 实例3. QTableView 的常用属性和方法

PyQt6/PySide6中QTreeView类的实现

《PyQt6/PySide6中QTreeView类的实现》QTreeView是PyQt6或PySide6库中用于显示分层数据的控件,本文主要介绍了PyQt6/PySide6中QTreeView类的实现... 目录1. 基本概念2. 创建 QTreeView 实例3. QTreeView 的常用属性和方法属性

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

pandas中位数填充空值的实现示例

《pandas中位数填充空值的实现示例》中位数填充是一种简单而有效的方法,用于填充数据集中缺失的值,本文就来介绍一下pandas中位数填充空值的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是中位数填充?为什么选择中位数填充?示例数据结果分析完整代码总结在数据分析和机器学习过程中,处理缺失数

Golang HashMap实现原理解析

《GolangHashMap实现原理解析》HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持高效的插入、查找和删除操作,:本文主要介绍GolangH... 目录HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持

Pandas使用AdaBoost进行分类的实现

《Pandas使用AdaBoost进行分类的实现》Pandas和AdaBoost分类算法,可以高效地进行数据预处理和分类任务,本文主要介绍了Pandas使用AdaBoost进行分类的实现,具有一定的参... 目录什么是 AdaBoost?使用 AdaBoost 的步骤安装必要的库步骤一:数据准备步骤二:模型

使用Pandas进行均值填充的实现

《使用Pandas进行均值填充的实现》缺失数据(NaN值)是一个常见的问题,我们可以通过多种方法来处理缺失数据,其中一种常用的方法是均值填充,本文主要介绍了使用Pandas进行均值填充的实现,感兴趣的... 目录什么是均值填充?为什么选择均值填充?均值填充的步骤实际代码示例总结在数据分析和处理过程中,缺失数

Java对象转换的实现方式汇总

《Java对象转换的实现方式汇总》:本文主要介绍Java对象转换的多种实现方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java对象转换的多种实现方式1. 手动映射(Manual Mapping)2. Builder模式3. 工具类辅助映

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服