iOS tableviewcell里点击文字展开与收起功能

2024-01-12 21:38

本文主要是介绍iOS tableviewcell里点击文字展开与收起功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

做项目遇到动态列表中需要做文字展开与收起功能,有空单独抽出一个demo给大家参考。
1、效果图如下:
在这里插入图片描述
在这里插入图片描述

2、创建tableview与添加数据

- (void)viewDidLoad {[super viewDidLoad];self.view.backgroundColor = [UIColor whiteColor];self.title = @"在tablecell中文本的展开与收起";self.allData = [NSMutableArray array];//添加子视图[self addSubViewUI];//请求数据[self requestMessageListData];//增加刷新[self addRefresh];
}

模拟请求数据

#pragma mark ==========请求数据==========
-(void)requestMessageListData{NSArray *arr = @[ ];for (int i = 0; i<10; i++) {HBTextChangeModel *model = [HBTextChangeModel new];model.content = arr[arc4random_uniform(10)];[self.allData addObject:model];}[self endRefresh];[self.tableView reloadData];
}

设置上拉加载,下拉刷新

- (void)endRefresh{if (self.tableView.mj_header.refreshing) {[self.tableView.mj_header endRefreshing];}if (self.tableView.mj_footer.refreshing) {[self.tableView.mj_footer endRefreshing];}
}
- (void)addRefresh{WEAKSELF;self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{//请求数据// weakSelf.pageNo = 1;[weakSelf.allData removeAllObjects];[weakSelf requestMessageListData];}];self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{//请求数据//weakSelf.pageNo++;[weakSelf requestMessageListData];}];
}

添加子视图

#pragma mark ==========添加子视图==========
-(void)addSubViewUI{[self.view addSubview:self.backBtn];[self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {make.top.equalTo(self.view).offset(20);make.left.equalTo(self.view).offset(15);make.size.mas_equalTo(CGSizeMake(100, 25));}];[self.view addSubview:self.tableView];[self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {make.top.equalTo(self.backBtn.mas_bottom);make.bottom.equalTo(self.view);make.left.right.equalTo(self.view);}];
}
#pragma mark ==========tableViewDelegate==========
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{return self.allData.count;
}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{return 1;
}#pragma mark ==========tableview代理方法==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{HBTextChangeTabCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HBTextChangeTabCell"];if (cell == nil) {cell = [[HBTextChangeTabCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HBTextChangeTabCell"];}cell.selectionStyle = UITableViewCellSelectionStyleNone;cell.backgroundColor = [UIColor clearColor];HBTextChangeModel *model = self.allData[indexPath.section];cell.model = model;WEAKSELF;cell.updateMessageCellBlock = ^(NSString * _Nonnull str) {[weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];};[cell layoutIfNeeded];return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{return UITableViewAutomaticDimension;
}- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {return 15;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{//全部商品UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 15)];headerView.backgroundColor = [UIColor grayColor];return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{//全部商品UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];footerView.backgroundColor = [UIColor clearColor];return footerView;
}-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{}#pragma mark ==========tableViewGetter==========
-(UITableView *)tableView{if (!_tableView) {_tableView = ({UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];tableView.dataSource = self;tableView.delegate = self;tableView.backgroundColor = [UIColor clearColor];//设置分割线样式tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;//cell的分割线距视图距离tableView.separatorInset=UIEdgeInsetsMake(0, 0, 0, 0);//隐藏底部多余分割线tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];//iOS11默认开启Self-Sizing,需关闭才能设置Header,Footer高度tableView.estimatedRowHeight = 66;tableView.estimatedSectionHeaderHeight = 0;tableView.estimatedSectionFooterHeight = 0;tableView.rowHeight = 50 ;tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];;tableView ;}) ;}return _tableView;
}
-(UIButton *)backBtn{if (!_backBtn) {_backBtn = ({//创建按钮UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];//设置标题[button setTitle:@"返回" forState:UIControlStateNormal];//设置字体大小button.titleLabel.font = [UIFont systemFontOfSize:14];//设置title颜色[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//添加点击事件[button addTarget:self action:@selector(clickBackButton:) forControlEvents:UIControlEventTouchUpInside];button;});}return _backBtn;
}
#pragma mark ==========点击返回==========
-(void)clickBackButton:(UIButton *)button{[self dismissViewControllerAnimated:YES completion:nil];
}

3、cell中的核心代码:

-(void)setModel:(HBTextChangeModel *)model{_model = model;NSString *desc = model.content;if (desc) {//计算文本高度CGFloat height = [desc heightWithStrAttri:@{NSFontAttributeName:FONT(15), NSForegroundColorAttributeName: Color_label_DataTitle,NSParagraphStyleAttributeName:[self paragraphStyle]} withLabelWidth:SCREEN_WIDTH];if (height > 67) { //超过3行if (model.showAll) {//拼接再算高度height = [[NSString stringWithFormat:@"%@...收起",desc] heightWithStrAttri:@{NSFontAttributeName:FONT(15), NSForegroundColorAttributeName: Color_label_DataTitle,NSParagraphStyleAttributeName:[self paragraphStyle]} withLabelWidth:SCREEN_WIDTH];[self.contentBaseView mas_updateConstraints:^(MASConstraintMaker *make) {make.height.mas_equalTo(height+5);}];self.contentLabel.truncationToken = nil;[self setShowTextWithDesc:desc];} else {[self.contentBaseView mas_updateConstraints:^(MASConstraintMaker *make) {make.height.mas_equalTo(67);}];[self setAdjustableTextWithDesc:desc];}} else {[self.contentBaseView mas_updateConstraints:^(MASConstraintMaker *make) {make.height.mas_equalTo(height+10);}];NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:desc attributes:@{ NSFontAttributeName:FONT(15), NSParagraphStyleAttributeName : [self paragraphStyle]}];self.contentLabel.attributedText = text;}}
}
- (void)setShowTextWithDesc:(NSString *)desc
{NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@...收起",desc] attributes:@{ NSFontAttributeName:FONT(15), NSParagraphStyleAttributeName : [self paragraphStyle]}];WEAKSELF;//设置高亮色和点击事件[text setTextHighlightRange:[[text string] rangeOfString:@"收起"] color:[UIColor colorWithHexString:@"#0099FF"] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {weakSelf.model.showAll = NO;if (self.updateMessageCellBlock) {self.updateMessageCellBlock(@"");}}];self.contentLabel.attributedText = text;
}- (NSMutableParagraphStyle *)paragraphStyle {NSMutableParagraphStyle *para = [NSMutableParagraphStyle new];para.lineSpacing = 5.f;return para;
}- (void)setAdjustableTextWithDesc:(NSString *)desc
{NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:desc attributes:@{ NSFontAttributeName:FONT(15), NSParagraphStyleAttributeName : [self paragraphStyle]}];self.contentLabel.attributedText = text;WEAKSELF;NSMutableAttributedString *showAll = [[NSMutableAttributedString alloc] initWithString:@"...展开" attributes:nil];YYTextHighlight *hi = [YYTextHighlight new];[hi setColor:[UIColor colorWithHexString:@"#009900"]];hi.tapAction = ^(UIView *containerView,NSAttributedString *text,NSRange range, CGRect rect) {weakSelf.model.showAll = YES;if (self.updateMessageCellBlock) {self.updateMessageCellBlock(@"");}};NSRange range = [showAll.string rangeOfString:@"展开"];[showAll setColor:[UIColor colorWithHexString:@"#0099FF"] range:range];[showAll setTextHighlight:hi range:range];showAll.font = FONT(15);YYLabel *seeMore = [YYLabel new];seeMore.attributedText = showAll;[seeMore sizeToFit];seeMore.height += 2.f;NSAttributedString *truncationToken = [NSAttributedString attachmentStringWithContent:seeMore contentMode:UIViewContentModeCenter attachmentSize:seeMore.frame.size alignToFont:FONT(15) alignment:YYTextVerticalAlignmentTop];self.contentLabel.truncationToken = truncationToken;
}

最后附上demo连接

END.

这篇关于iOS tableviewcell里点击文字展开与收起功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

Qt实现对Word网页的读取功能

《Qt实现对Word网页的读取功能》文章介绍了几种在Qt中实现Word文档(.docx/.doc)读写功能的方法,包括基于QAxObject的COM接口调用、DOCX模板替换及跨平台解决方案,重点讨论... 目录1. 核心实现方式2. 基于QAxObject的COM接口调用(Windows专用)2.1 环境

SpringBoot+Vue3整合SSE实现实时消息推送功能

《SpringBoot+Vue3整合SSE实现实时消息推送功能》在日常开发中,我们经常需要实现实时消息推送的功能,这篇文章将基于SpringBoot和Vue3来简单实现一个入门级的例子,下面小编就和大... 目录前言先大概介绍下SSE后端实现(SpringBoot)前端实现(vue3)1. 数据类型定义2.

SpringBoot整合Apache Spark实现一个简单的数据分析功能

《SpringBoot整合ApacheSpark实现一个简单的数据分析功能》ApacheSpark是一个开源的大数据处理框架,它提供了丰富的功能和API,用于分布式数据处理、数据分析和机器学习等任务... 目录第一步、添加android依赖第二步、编写配置类第三步、编写控制类启动项目并测试总结ApacheS

Python实现繁体转简体功能的三种方案

《Python实现繁体转简体功能的三种方案》在中文信息处理中,繁体字与简体字的转换是一个常见需求,无论是处理港澳台地区的文本数据,还是开发面向不同中文用户群体的应用,繁简转换都是不可或缺的功能,本文将... 目录前言为什么需要繁简转换?python实现方案方案一:使用opencc库方案二:使用zhconv库

Qt实现删除布局与布局切换功能

《Qt实现删除布局与布局切换功能》在Qt应用开发中,动态管理布局是一个常见需求,比如根据用户操作动态删除某个布局,或在不同布局间进行切换,本文将详细介绍如何实现这些功能,并通过完整示例展示具体操作,需... 目录一、Qt动态删除布局1. 布局删除的注意事项2. 动态删除布局的实现步骤示例:删除vboxLay

Spring Boot整合Redis注解实现增删改查功能(Redis注解使用)

《SpringBoot整合Redis注解实现增删改查功能(Redis注解使用)》文章介绍了如何使用SpringBoot整合Redis注解实现增删改查功能,包括配置、实体类、Repository、Se... 目录配置Redis连接定义实体类创建Repository接口增删改查操作示例插入数据查询数据删除数据更

使用EasyPoi快速导出Word文档功能的实现步骤

《使用EasyPoi快速导出Word文档功能的实现步骤》EasyPoi是一个基于ApachePOI的开源Java工具库,旨在简化Excel和Word文档的操作,本文将详细介绍如何使用EasyPoi快速... 目录一、准备工作1、引入依赖二、准备好一个word模版文件三、编写导出方法的工具类四、在Export

JS纯前端实现浏览器语音播报、朗读功能的完整代码

《JS纯前端实现浏览器语音播报、朗读功能的完整代码》在现代互联网的发展中,语音技术正逐渐成为改变用户体验的重要一环,下面:本文主要介绍JS纯前端实现浏览器语音播报、朗读功能的相关资料,文中通过代码... 目录一、朗读单条文本:① 语音自选参数,按钮控制语音:② 效果图:二、朗读多条文本:① 语音有默认值:②

C#实现高性能拍照与水印添加功能完整方案

《C#实现高性能拍照与水印添加功能完整方案》在工业检测、质量追溯等应用场景中,经常需要对产品进行拍照并添加相关信息水印,本文将详细介绍如何使用C#实现一个高性能的拍照和水印添加功能,包含完整的代码实现... 目录1. 概述2. 功能架构设计3. 核心代码实现python3.1 主拍照方法3.2 安全HBIT