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

相关文章

Debian 13升级后网络转发等功能异常怎么办? 并非错误而是管理机制变更

《Debian13升级后网络转发等功能异常怎么办?并非错误而是管理机制变更》很多朋友反馈,更新到Debian13后网络转发等功能异常,这并非BUG而是Debian13Trixie调整... 日前 Debian 13 Trixie 发布后已经有众多网友升级到新版本,只不过升级后发现某些功能存在异常,例如网络转

基于Java和FFmpeg实现视频压缩和剪辑功能

《基于Java和FFmpeg实现视频压缩和剪辑功能》在视频处理开发中,压缩和剪辑是常见的需求,本文将介绍如何使用Java结合FFmpeg实现视频压缩和剪辑功能,同时去除数据库操作,仅专注于视频处理,需... 目录引言1. 环境准备1.1 项目依赖1.2 安装 FFmpeg2. 视频压缩功能实现2.1 主要功

使用Python实现无损放大图片功能

《使用Python实现无损放大图片功能》本文介绍了如何使用Python的Pillow库进行无损图片放大,区分了JPEG和PNG格式在放大过程中的特点,并给出了示例代码,JPEG格式可能受压缩影响,需先... 目录一、什么是无损放大?二、实现方法步骤1:读取图片步骤2:无损放大图片步骤3:保存图片三、示php

深度解析Python yfinance的核心功能和高级用法

《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?

Python脚本轻松实现检测麦克风功能

《Python脚本轻松实现检测麦克风功能》在进行音频处理或开发需要使用麦克风的应用程序时,确保麦克风功能正常是非常重要的,本文将介绍一个简单的Python脚本,能够帮助我们检测本地麦克风的功能,需要的... 目录轻松检测麦克风功能脚本介绍一、python环境准备二、代码解析三、使用方法四、知识扩展轻松检测麦

Java实现TXT文件导入功能的详细步骤

《Java实现TXT文件导入功能的详细步骤》在实际开发中,很多应用场景需要将用户上传的TXT文件进行解析,并将文件中的数据导入到数据库或其他存储系统中,本文将演示如何用Java实现一个基本的TXT文件... 目录前言1. 项目需求分析2. 示例文件格式3. 实现步骤3.1. 准备数据库(假设使用 mysql

Springboot项目登录校验功能实现

《Springboot项目登录校验功能实现》本文介绍了Web登录校验的重要性,对比了Cookie、Session和JWT三种会话技术,分析其优缺点,并讲解了过滤器与拦截器的统一拦截方案,推荐使用JWT... 目录引言一、登录校验的基本概念二、HTTP协议的无状态性三、会话跟android踪技术1. Cook

基于Spring Boot 的小区人脸识别与出入记录管理系统功能

《基于SpringBoot的小区人脸识别与出入记录管理系统功能》文章介绍基于SpringBoot框架与百度AI人脸识别API的小区出入管理系统,实现自动识别、记录及查询功能,涵盖技术选型、数据模型... 目录系统功能概述技术栈选择核心依赖配置数据模型设计出入记录实体类出入记录查询表单出入记录 VO 类(用于

Qt中实现多线程导出数据功能的四种方式小结

《Qt中实现多线程导出数据功能的四种方式小结》在以往的项目开发中,在很多地方用到了多线程,本文将记录下在Qt开发中用到的多线程技术实现方法,以导出指定范围的数字到txt文件为例,展示多线程不同的实现方... 目录前言导出文件的示例工具类QThreadQObject的moveToThread方法实现多线程QC

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的