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实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too