展开label,利用YYText实现文字显示不完末尾添加全文
效果图:
操作
先github下载<YYText>文件导入,
代码如下:
#import "ViewController.h" #import "YYLabel.h" #import "NSAttributedString+YYText.h" #import <UIKit/UIKit.h> @interface ViewController () @property (nonatomic,strong) YYLabel *label;; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSMutableAttributedString *text = [NSMutableAttributedString new]; UIFont *font = [UIFont systemFontOfSize:16]; // 添加文本 NSString *title = @"dwwdqwddqdqdqdqwdqdqwdqwdqdqdqdqwdqwdqdqdqwdqdqwdqdqdqdqdqdqwdq当前的群无多群无多群无多群无多群无多群多群无多群无多群无多群无多群多群多群多群当前的群无多群多群无多群多群多群多群多群多群多群多群的权威的权威的期望多无群多群无多群多群多群多群无多群无多群无多群无多群无多群无多群多群无多群无多群多群无多群多群无多无多无群多多群无多群多群多群多群无多群多无!"; [text appendAttributedString:[[NSAttributedString alloc] initWithString:title attributes:nil]]; text.yy_font = font ; _label = [YYLabel new]; _label.userInteractionEnabled = YES; _label.numberOfLines = 0; _label.textVerticalAlignment = YYTextVerticalAlignmentTop; _label.frame = CGRectMake(40,60, self.view.frame.size.width-80,150); _label.attributedText = text; [self.view addSubview:_label]; _label.layer.borderWidth = 0.5; _label.layer.borderColor = [UIColor colorWithRed:0.000 green:0.463 blue:1.000 alpha:1.000].CGColor; // 添加全文 [self addSeeMoreButton]; } #pragma mark - 添加全文 - (void)addSeeMoreButton { __weak __typeof(self) weakSelf = self; NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"...全文"]; YYTextHighlight *hi = [YYTextHighlight new]; [hi setColor:[UIColor colorWithRed:0.578 green:0.790 blue:1.000 alpha:1.000]]; hi.tapAction = ^(UIView *containerView,NSAttributedString *text,NSRange range, CGRect rect) {
// 点击全文回调 YYLabel *label = weakSelf.label; [label sizeToFit]; }; [text yy_setColor:[UIColor colorWithRed:0.000 green:0.449 blue:1.000 alpha:1.000] range:[text.string rangeOfString:@"全文"]]; [text yy_setTextHighlight:hi range:[text.string rangeOfString:@"全文"]]; text.yy_font = _label.font; YYLabel *seeMore = [YYLabel new]; seeMore.attributedText = text; [seeMore sizeToFit]; NSAttributedString *truncationToken = [NSAttributedString yy_attachmentStringWithContent:seeMore contentMode:UIViewContentModeCenter attachmentSize:seeMore.frame.size alignToFont:text.yy_font alignment:YYTextVerticalAlignmentCenter]; _label.truncationToken = truncationToken; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· DeepSeek+PageAssist实现本地大模型联网
· 手把手教你更优雅的享受 DeepSeek
· Java轻量级代码工程
· 从 14 秒到 1 秒:MySQL DDL 性能优化实战