效果:

====直接上代码吧===

//
//  UILabel+StringFrame.h
//  QYER
//
//  Created by qyer on 15/3/19.
//  Copyright (c) 2015年 QYER. All rights reserved.
//#import <UIKit/UIKit.h>/***  uilable 行间距高度*/
static CGFloat const lineSapceHeight = 5.0f;@interface UILabel (StringFrame)#pragma mark - 获取UILable Size- (CGSize)boundingRectWithSize:(CGSize)size;
/***  根据文字长度计算大小**  @param content 文字长度*  @param pFont   文字字号*  @param pWidth  宽度**/
+(CGSize)getContentSize:(NSString *)content font:(UIFont *)pFont width:(CGFloat)pWidth;
/***  根据文字长度计算大小**  @param content 文字长度*  @param pFont   文字字号*  @param pHeight  高度**/
+(CGSize)getContentSize:(NSString *)content font:(UIFont *)pFont height:(CGFloat)pHeight;
/***  根据文本获取size ,有最大 宽高限制**  @param string    文本*  @param maxWidth  最大宽*  @param maxHeight 最大高*  @param font      字体*  @param lineSpace 行间距(如果使用默认的,就传nil)**  @return size*/
+(CGSize)getContentSizeWithContentText:(NSString *)string andMaxWidth:(CGFloat)maxWidth andMaxHeight:(CGFloat)maxHeight AndFont:(UIFont*)font andLineSpacing:(NSNumber *)lineSpace; /** * 根据文本获取size ,有最大 宽高限制 * * @param string 文本 * @param maxWidth 最大宽 * @param maxHeight 最大高 * @param attribute 富文本属性 * * @return size */ +(CGSize)getContentSizeWithContentText:(NSString *)string andMaxWidth:(CGFloat)maxWidth andMaxHeight:(CGFloat)maxHeight andAttributes:(NSDictionary *)attribute; #pragma mark - 获取UILable 每行显示的文字 /** * 获取lalbe 每行文字 * * @return 每行文字数组 */ - (NSArray *)getSeparatedLines; /** * 获取lalbe 每行文字 * * @param text 根据文字内容 * * @return 每行文字数组 */ - (NSArray *)getSeparatedLinesWithText:(NSString*)text; /** * 获取lalbe 每行文字 * * @param content 文字内容 * @param fonte fonte description * @param size size description * * @return return value description */ +(NSArray *)getSeparatedLinesWithText:(NSString*)content andFonte:(UIFont *)fonte andSize:(CGSize)size; #pragma mark - 完美解决 向UILable 文字最后插入N张图片,支持向限制行数的UILable 最后一行插入,多余文字显示... /** * 向文字末尾追加图片,适用于已知Size的UILable * * @param contentStr 文字内容 * @param imgs 插入的图片数组, 图片最好带间隔哦 */ -(void)insertImgToContentLast:(NSString *)contentStr imgs:(NSArray *)imgs; /** * 向文字末尾追加图片,适用于AutoLayout 的UILable * * @param contentStr 文字内容 * @param imgs 插入的图片数组, 图片最好带间隔哦 * @param estimateWidth 预估的UILable 最大宽度(已知的最大宽度) */ -(void)insertImgToContentLast:(NSString *)contentStr imgs:(NSArray *)imgs estimateWidth:(CGFloat)estimateWidth; /** * 向已知文字后插入图片 * * @param insertImgArr insertImgArr description * @param appendAttributedString 可为nil */ -(void)configTitleLableAttributedString:(NSArray *)insertImgArr AttributedString:(NSMutableAttributedString *)appendAttributedString; @end

//
//  UILabel+StringFrame.m
//  QYER
//
//  Created by qyer on 15/3/19.
//  Copyright (c) 2015年 QYER. All rights reserved.
//#import "UILabel+StringFrame.h"#import <CoreText/CoreText.h>@implementation UILabel (StringFrame)#pragma mark - 获取UILable Size- (CGSize)boundingRectWithSize:(CGSize)size
{NSDictionary *attribute = @{NSFontAttributeName: self.font};CGSize retSize = [self.text boundingRectWithSize:sizeoptions:\NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size; return retSize; } +(CGSize)getContentSize:(NSString *)content font:(UIFont *)pFont width:(CGFloat)pWidth{ CGSize contentSize; if (ios7) { contentSize = [content boundingRectWithSize:CGSizeMake(pWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:pFont,NSFontAttributeName, nil] context:nil].size; }else{ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" contentSize = [content sizeWithFont:pFont constrainedToSize:CGSizeMake(pWidth, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping]; #pragma clang diagnostic pop } return contentSize; } +(CGSize)getContentSize:(NSString *)content font:(UIFont *)pFont height:(CGFloat)pHeight{ CGSize contentSize; if (ios7) { contentSize = [content boundingRectWithSize:CGSizeMake(MAXFLOAT, pHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:pFont,NSFontAttributeName, nil] context:nil].size; }else{ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" contentSize = [content sizeWithFont:pFont constrainedToSize:CGSizeMake(MAXFLOAT, pHeight) lineBreakMode:NSLineBreakByCharWrapping]; #pragma clang diagnostic pop } return contentSize; } /** * 根据文本获取size ,有最大 宽高限制 * * @param string 文本 * @param maxWidth 最大宽 * @param maxHeight 最大高 * @param attribute 富文本属性 * * @return size */ +(CGSize)getContentSizeWithContentText:(NSString *)string andMaxWidth:(CGFloat)maxWidth andMaxHeight:(CGFloat)maxHeight andAttributes:(NSDictionary *)attribute{ CGSize size = CGSizeZero; if (IsEmpty(string)) { return size; } if (string) { if ([string respondsToSelector: @selector(boundingRectWithSize:options:attributes:context:)]) { size = [string boundingRectWithSize:CGSizeMake(maxWidth, maxHeight) options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesFontLeading attributes:attribute context:nil].size; }else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" size = [string sizeWithFont:attribute[@"NSFontAttributeName"] constrainedToSize:CGSizeMake(maxWidth, maxHeight) lineBreakMode:NSLineBreakByCharWrapping]; #pragma clang diagnostic pop } } if (!CGSizeEqualToSize(CGSizeZero, size)) { CGFloat wight = maxWidth; CGFloat height = ceil(size.height); /** * 使用 NIAttributedLabel 有个bug ,当文字只有一行或不满一行 会出现文字显示不出来 */ if (!attribute) { NSArray *rows = [UILabel getSeparatedLinesWithText:string andFonte:attribute[NSFontAttributeName] andSize:size]; if ([rows count]==1) { CGSize offsetSize = [UILabel getContentSize:string font:attribute[NSFontAttributeName] width:maxWidth]; size = CGSizeMake(ceil(offsetSize.width) , ceil(offsetSize.height)); }else{ size = CGSizeMake(wight ,height); } }else { size = CGSizeMake(wight ,height); } } return size; } /** * 根据文本获取size ,有最大 宽高限制 * * @param string 文本 * @param maxWidth 最大宽 * @param maxHeight 最大高 * @param font 字体 * @param lineSpace 行间距(如果使用默认的,就传nil) * * @return size */ +(CGSize)getContentSizeWithContentText:(NSString *)string andMaxWidth:(CGFloat)maxWidth andMaxHeight:(CGFloat)maxHeight AndFont:(UIFont*)font andLineSpacing:(NSNumber *)lineSpace{ CGSize size = CGSizeZero; if (IsEmpty(string)) { return size; } if (string && font) { if ([string respondsToSelector: @selector(boundingRectWithSize:options:attributes:context:)]) { NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; paragraphStyle.alignment = NSTextAlignmentLeft; if (lineSpace) { paragraphStyle.lineSpacing = [lineSpace floatValue]; } size = [string boundingRectWithSize:CGSizeMake(maxWidth, maxHeight) options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle} context:nil].size; }else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" size = [string sizeWithFont:font constrainedToSize:CGSizeMake(maxWidth, maxHeight) lineBreakMode:NSLineBreakByCharWrapping]; #pragma clang diagnostic pop } } if (!CGSizeEqualToSize(CGSizeZero, size)) { CGFloat wight = ceil(maxWidth); CGFloat height = ceil(size.height ); /** * 使用 NIAttributedLabel 有个bug ,当文字只有一行或不满一行 会出现文字显示不出来 */ NSArray *rows = [UILabel getSeparatedLinesWithText:string andFonte:font andSize:size]; if ([rows count]==1) { CGSize offsetSize = [UILabel getContentSize:string font:font width:maxWidth]; size = CGSizeMake(ceil(offsetSize.width) , ceil(offsetSize.height)); }else{ size = CGSizeMake(wight ,height); } } return size; } #pragma mark - 获取UILable 每行显示的文字 /** * 获取lalbe 每行文字 * * @return 每行文字数组 */ - (NSArray *)getSeparatedLines { return [self getSeparatedLinesWithText:self.text]; } /** * 获取lalbe 每行文字 * * @param text 根据文字内容 * * @return 每行文字数组 */ - (NSArray *)getSeparatedLinesWithText:(NSString*)text { /** * fix NSConcreteMutableAttributedString initWithString:: nil value */ if (!(text && [text isKindOfClass:[NSString class]])) { return nil; } return [UILabel getSeparatedLinesWithText:text andFonte:[self font] andSize:[self frame].size]; } /** * 获取lalbe 每行文字 * * @param content 文字内容 * @param fonte fonte description * @param size size description * * @return 每行文字数组 */ +(NSArray *)getSeparatedLinesWithText:(NSString*)content andFonte:(UIFont *)fonte andSize:(CGSize)size{ if (!(content&&[content isKindOfClass:[NSString class]]) || !(fonte&& [fonte isKindOfClass:[UIFont class]]) || CGSizeEqualToSize(CGSizeZero, size)) { return nil; } NSString *text = content; UIFont *font = fonte; CGRect rect = CGRectMake(0, 0, size.width,size.height); CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL); NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text]; [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)]; CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr); CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000)); CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL); NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame); NSMutableArray *linesArray = [[NSMutableArray alloc]init]; for (id line in lines) { CTLineRef lineRef = (__bridge CTLineRef )line; CFRange lineRange = CTLineGetStringRange(lineRef); NSRange range = NSMakeRange(lineRange.location, lineRange.length); NSString *lineString = [text substringWithRange:range]; [linesArray addObject:lineString]; } CFRelease(frameSetter); CFRelease(myFont); CFRelease(frame); CFRelease(path); return (NSArray *)linesArray; } #pragma mark - 完美解决 向UILable 文字最后插入N张图片,支持向限制行数的UILable 最后一行插入,多余文字显示... /** * 向文字末尾追加图片,适用于已知Size的UILable * * @param contentStr 文字内容 * @param imgs 插入的图片数组, 图片最好带间隔哦 */ -(void)insertImgToContentLast:(NSString *)contentStr imgs:(NSArray *)imgs{ if (IsEmpty(contentStr) || !imgs || [imgs count] == 0) { self.text = IsEmpty(contentStr)?@"":contentStr; return ; } [self insertImgToContentLast:contentStr imgs:imgs estimateWidth:[self frame].size.width]; } /** * 向文字末尾追加图片,适用于AutoLayout 的UILable * * @param contentStr 文字内容 * @param imgs 插入的图片数组, 图片最好带间隔哦 * @param estimateWidth 预估的UILable 最大宽度(已知的最大宽度) */ -(void)insertImgToContentLast:(NSString *)contentStr imgs:(NSArray *)imgs estimateWidth:(CGFloat)estimateWidth{ if (IsEmpty(contentStr) || !imgs || [imgs count] == 0 || estimateWidth == 0) { self.text = IsEmpty(contentStr)?@"":contentStr; return ; } //获取每行文字需要预设宽度,不然每个字都会是单独的一行 self.width = estimateWidth; NSArray *textLineArr = [self getSeparatedLinesWithText:contentStr]; NSInteger maxLine = self.numberOfLines; if (maxLine == 0) { self.text = contentStr; //追加图片  [self configTitleLableAttributedString:imgs AttributedString:nil]; return; } NSInteger lastLineIndex = maxLine - 1; if ([textLineArr count] <= lastLineIndex) { self.text = contentStr; //追加图片  [self configTitleLableAttributedString:imgs AttributedString:nil]; return; } __block CGFloat imgWith = 0.0; [imgs enumerateObjectsUsingBlock:^(UIImage* img, NSUInteger idx, BOOL * _Nonnull stop) { imgWith += img.size.width; }]; CGFloat lastTextMaxWith = estimateWidth - imgWith; if (lastTextMaxWith <= 0) { self.text = contentStr; //追加图片  [self configTitleLableAttributedString:imgs AttributedString:nil]; return ; } if ([textLineArr count] > lastLineIndex) { NSMutableString *muShowTitle = [NSMutableString string]; [textLineArr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { if (idx > (lastLineIndex - 1)) { //预设宽度 self.width = lastTextMaxWith; //最大宽带下能显示的字数 NSArray *lastLineArr = [self getSeparatedLinesWithText:textLineArr[lastLineIndex]]; NSString *lastLineText = lastLineArr[0]; // DDLogDebug(@"====lastLineText=======%@==",lastLineText); if ([lastLineArr count] > 1) { lastLineText = [lastLineText stringByReplacingCharactersInRange:NSMakeRange(lastLineText.length - 3, 3) withString:@"..."]; } // DDLogDebug(@"====lastLineArr[0]=======%@==",lastLineText);  [muShowTitle appendString:lastLineText]; * stop = YES; return ; } [muShowTitle appendString:textLineArr[idx]]; }]; self.text = muShowTitle; // self.width = estimateWidth;  } //追加图片  [self configTitleLableAttributedString:imgs AttributedString:nil]; } /** * 向已知文字后插入图片 * * @param insertImgArr insertImgArr description * @param appendAttributedString 可为nil */ -(void)configTitleLableAttributedString:(NSArray *)insertImgArr AttributedString:(NSMutableAttributedString *)appendAttributedString{ if (!insertImgArr || [insertImgArr count] == 0) { return ; } if (!appendAttributedString) { appendAttributedString = [[NSMutableAttributedString alloc] initWithString:self.text]; } [insertImgArr enumerateObjectsUsingBlock:^(UIImage* img, NSUInteger idx, BOOL * _Nonnull stop) { NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init]; //带 x 的 textAttachment.image = img; CGFloat mid = self.font.descender + self.font.capHeight; CGFloat imgY = self.font.descender - textAttachment.image.size.height/2 + mid + 2; textAttachment.bounds = CGRectMake(0, imgY, textAttachment.image.size.width, textAttachment.image.size.height); NSAttributedString *iconAttributedString = [NSAttributedString attributedStringWithAttachment:textAttachment]; [appendAttributedString replaceCharactersInRange:NSMakeRange(self.text.length, 0) withAttributedString:iconAttributedString]; /** fix,当文字刚好够一行,添加图片后折行,but.第二行图片和第一行文字没有行间距。。 http://scottzhu.com/blog/2015/02/14/attach-stars-to-the-end-of-a-uilabel/ */ [appendAttributedString appendAttributedString: [[NSAttributedString alloc] initWithString:@" "]]; }]; self.attributedText = appendAttributedString; } @end

转载于:https://www.cnblogs.com/DamonTang/p/5344048.html

完美解决 向UILable 文字最后插入N张图片,支持向限制行数的UILable 最后一行插入,多余文字显示......相关推荐

  1. 完美解决移动Web小于12px文字居中的问题

    前几天的一篇博文:移动Web单行文字垂直居中的问题,提到了移动web里小于12px的文字居中异常的问题,最后还是改为12px才近乎解决了问题.但是有时候或许并不是那么乐观,你并不能将原本定为10px的 ...

  2. php 重复写入数据,完美解决Thinkphp3.2中插入相同数据的问题

    问题描述 今天在使用TP3.2插入数据的时候,为了避免插入相同的数据(所谓相同的数据,其主键相同或者是唯一索引的字段相同),我创建的索引如下图,主键索引为自增字段,不可能出现重复,即唯一索引可能会出现 ...

  3. Word图片插入后只显示最底下一行,输入文字后后面的文字不见了(解决办法(全程简洁无废话))

    问题1:图片插入后,只显示最底下一行 问题2:输入文字后,后面的文字不见了 问题1:图片插入后,只显示最底下一行 如下图: 解决办法: ① 选中图片,并选择"段落" ② 行距修改为 ...

  4. Python:matplotlib pyplot库函数 savefig所支持的格式以及图片插入word保存后模糊的完美解决方法

    Python:matplotlib pyplot库函数 savefig所支持的格式以及图片插入word保存后模糊的完美解决方法 202012月更新 savefig支持的格式 图片插入word,保存后不 ...

  5. android点击下拉历史记录,uni-app,社交应用中,聊天页面下拉onPullDownRefresh获取历史消息,数据合并之后,滚动到下拉之前的位置,页面看不见闪动,完美解决...

    一般下拉之后,拿到数据合并,会默认展示顶部第一条,模仿其他聊天应用,回到下拉之前位置,如果不做处理,可以看见下拉得到的数据,本方法完美解决 有问题可以留言或者加qq445849201讨论,亲测ios和 ...

  6. 毕设时,在word中插入图片时,图片的格式改成嵌入式后图片藏于文字下方怎么办?

    在写毕业论文时,插入的图片可以正常显示,但是当更改了论文的格式,将段落间距改为固定值20磅时,图片就出现问题,遇到这种问题的怎么办? 原理:word中图片的格式和文字段落的格式有密切的联系 在使用wo ...

  7. 2021-09-15核芯物联推荐生态合作伙伴莱讯科技#蓝牙AoA微信小程序跨楼层高精度定位导航,支持ibeacon+aoa融合,完美解决ibeacon导航存在的覆盖盲区

    2021-09-15核芯物联推荐生态合作伙伴莱讯科技#蓝牙AoA微信小程序跨楼层高精度定位导航,支持ibeacon+aoa融合,完美解决ibeacon导航存在的覆盖盲区 核芯物联推荐生态合作伙伴莱讯科 ...

  8. 如何在Word里的字母上方添加特殊符号——“拼音指南”+“切换域代码”完美解决!

    有时候我们为了在行文中加入一些希腊文字表示特定变量,同时要求在希腊文字上方插入一些特殊符号,为了解决随之出现的行间距变大问题,我们可以使用"拼音指南"+"切换域代码&qu ...

  9. oracle 如何边看表中字段信息_【Oracle移行到Sqlserver完美解决案】④sqluldr2+bulk 32H=3H...

    在[Oracle移行到Sqlserver完美解决案]③执行时间改善案bcp+bulk 一文中,移行实现了,但数据600多万件,占内存3G多的操作log表,移行需要32H,这个时间我们是无法接受的. 原 ...

最新文章

  1. R语言实战-统计分析基础-描述性统计4-psych-describe
  2. Android怎么插手机卡,魅蓝E手机卡怎么装 魅蓝E手机SIM卡安装图文教程
  3. Storm集群安装Version1.0.1
  4. 中国历史上唯一没有贪污的王朝
  5. DataTemplate 以及Template Selector 学习笔记
  6. oracle mysql数据库管理工具下载_Oracle数据库管理工具PC版-Oracle数据库管理工具下载v15.0.21.0(32/64)-IE浏览器中文网站...
  7. 语言怎么搜包的源代码_大四学生发明文言文编程语言,设计思路清奇
  8. java 点云数据处理_概述 | 点云数据处理方法都有哪些?
  9. Java中获取当前时间、昨天、三天前、一周前、一月前时间(2)
  10. 邮箱163登录入口,邮箱163如何注册?
  11. Linux驱动学习--初识PCI驱动(一)
  12. TSL2561 GY2561 模块 MSP430 单片机 程序 STM32 程序 光强传感器 MSP430F5529
  13. Matlab 7 win7安装步骤
  14. 大连将在东京建设软件园
  15. Three.js——天空盒
  16. C++学习 控制程序的流程
  17. 步进电机的使用教程以及步距角和细分讲解
  18. LeakCanary源码解析
  19. 带上卡旺达户外电源 来一场“人类高质量野营”
  20. least(exp1,exp2,exp3,……,expn)

热门文章

  1. jQuery的选择器——可见性过滤选择器
  2. 机房收费系统中——存储过程中加入事务,实现学生注册
  3. golang中的plugin包
  4. golang输入命令行参数
  5. muduo之channel
  6. 口语学习Day7:今天聊聊美国超市的物价
  7. 以太币(Ether)的单位
  8. linux:内核中断
  9. 《编码:隐匿在计算机软硬件背后的语言(美)》读书笔记四
  10. Linux学习日记之sshd服务