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

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

认识、理解、分类——acm之搜索

普通搜索方法有两种:1、广度优先搜索;2、深度优先搜索; 更多搜索方法: 3、双向广度优先搜索; 4、启发式搜索(包括A*算法等); 搜索通常会用到的知识点:状态压缩(位压缩,利用hash思想压缩)。

hdu1240、hdu1253(三维搜索题)

1、从后往前输入,(x,y,z); 2、从下往上输入,(y , z, x); 3、从左往右输入,(z,x,y); hdu1240代码如下: #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#inc

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

安卓链接正常显示,ios#符被转义%23导致链接访问404

原因分析: url中含有特殊字符 中文未编码 都有可能导致URL转换失败,所以需要对url编码处理  如下: guard let allowUrl = webUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {return} 后面发现当url中有#号时,会被误伤转义为%23,导致链接无法访问