最近有個(gè)需求,類似微博內(nèi)容的全文展開(kāi)功能,當(dāng)文本內(nèi)容超過(guò)3行時(shí)湃交,只展示兩行熟空,在第二行最后面加上...全文,然后點(diǎn)擊全文巡揍,展開(kāi)全部的文本內(nèi)容。
接到這個(gè)需求菌瘪,我們簡(jiǎn)單分析下腮敌,這個(gè)需求的難點(diǎn)在于在第二行文本的上加上...全文
,這里我們就必須知道第二行展示的文本內(nèi)容,然后判斷文本內(nèi)容長(zhǎng)度加上...全文
是否超過(guò)文本限制寬度俏扩,如果超過(guò)糜工,就需要對(duì)第二行原來(lái)的文本進(jìn)行截取,然后再拼接上...全文
,正好滿足一行的顯示,然后讓...全文
字符串響應(yīng)點(diǎn)擊事件來(lái)更新字符串录淡。
具體詳見(jiàn): DEMO
一. 如何知道第二行展示的文本內(nèi)容
要知道第二行展示的文本內(nèi)容烈疚,這個(gè)問(wèn)題等同于我們需要知道字符串在每一行文本的展示內(nèi)容躯概,
要知道字符串在每一行文本的展示內(nèi)容,我們可以利用
CoreText
。首先創(chuàng)建攜帶字體信息的字符串富文本夹抗,然后依據(jù)富文本生成
CTFramesetterRef frameSetter
接著創(chuàng)建
CGMutablePathRef path
,并限定繪制范圍利用
frameSetter 和 path
通過(guò)CTFramesetterCreateFrame
方法獲取得到CTFrameRef frame
利用
CTFrameRef frame
通過(guò)CTFrameGetLines
獲取CTLineRef
的數(shù)組lines
遍歷
lines
,獲取每一行l(wèi)ines的范圍NSRange range
,利用范圍簇秒,從原始字符串中截取對(duì)應(yīng)字符串溯泣,放到字符串?dāng)?shù)組里面linesArray
,之后釋放對(duì)應(yīng)的
path 、 frame窍帝、frameSetter
并返回linesArray
努潘。最后我們可以從字符串?dāng)?shù)組
linesArray
里面獲取第二行字符串的文本內(nèi)容。
對(duì)應(yīng)代碼如下:
+ (NSArray *)fjf_lineStringArrayWithLimitWidth:(CGFloat)limitWidth
contentFont:(UIFont *)contentFont
contentText:(NSString *)contentText {
if (contentText == nil) {
return nil;
}
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:contentText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
[attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
[attStr addAttribute:NSFontAttributeName value:contentFont range:NSMakeRange(0, attStr.length)];
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attStr);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0, 0, limitWidth, CGFLOAT_MAX));
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
NSArray *lines = (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 = [contentText substringWithRange:range];
[linesArray addObject:lineString];
}
CGPathRelease(path);
CFRelease(frame);
CFRelease(frameSetter);
return linesArray;
}
二. 對(duì)第二行字符串的截取并拼接...全文
當(dāng)我們獲取到第二行文本字符串之后坤学,我們解決的就是將...全文
拼接在合適的文本字符串的后面疯坤,這里包括幾種情況。
當(dāng)?shù)诙形谋咀址唇由?code>...全文不超過(guò)限制寬度深浮,同時(shí)文本最后不是換行符
\n
压怠,就直接拼接。當(dāng)?shù)诙形谋咀址唇由?code>...全文不超過(guò)限制寬度飞苇,同時(shí)文本最后是換行符
\n
刑峡,將換行符\n
置位空,再拼接玄柠。當(dāng)?shù)诙形谋咀址唇由?code>...全文超過(guò)限制寬度突梦,需要將原先的字符串截取,截取剛好的長(zhǎng)度羽利,然后再拼接上
...全文
宫患,使得整個(gè)文本字符串不超過(guò)限制寬度。截取的時(shí)候需要注意因?yàn)樽址赡馨兄形恼饣 ⒆帜竿尴小?shù)字虚汛、表情等,所以截取的字符串長(zhǎng)度需要適合的計(jì)算皇帮,比如說(shuō)遇到表情就需要截取兩個(gè)字符長(zhǎng)度卷哩,同時(shí)截取的字符串長(zhǎng)度再拼接上
...全文
,并不一定能剛好占據(jù)整個(gè)限制寬度属拾,可能會(huì)有些偏差将谊,因?yàn)闈h字、表情占據(jù)的寬度比較寬渐白。
對(duì)應(yīng)代碼如下:
+ (NSInteger)fjf_trailBlankStringWithString:(NSString *)string
limitWidth:(CGFloat)limitWidth
contentFont:(UIFont *)contentFont
trailingBlankWidth:(CGFloat)trailingBlankWidth {
NSInteger currentStringLength = 0;
NSInteger subStrValueLength = 0;
while (currentStringLength <= string.length) {
NSString *tmpString = [string substringWithRange:NSMakeRange(0, currentStringLength)];
CGFloat stringWidth = [FJFExpandLabelTool fjf_widthForFont:contentFont maxWidth:limitWidth contentText:tmpString];
if (stringWidth > trailingBlankWidth) {
break;
}
NSString *tmpBalanceString = [string substringWithRange:NSMakeRange(0, string.length - currentStringLength)];
subStrValueLength = [self fjf_reduceStringLengthWithString:tmpBalanceString];
currentStringLength = currentStringLength + subStrValueLength;
}
return currentStringLength;
}
// 減去 字符 長(zhǎng)度
+ (NSInteger)fjf_reduceStringLengthWithString:(NSString *)string {
NSInteger subStrValue = 0;
if (string.length > 2) {
NSString *subStr = [string substringWithRange:NSMakeRange(string.length - 2, 2)];
if ([FJFExpandLabelTool fjf_isContainEmojiWithString:subStr]) {
subStrValue = 2;
} else {
subStrValue = 1;
}
}
return subStrValue;
}
+ (BOOL)fjf_isContainEmojiWithString:(NSString *)string {
if ([self fjf_matchEmojiRegularWithWithString:string]) {
return YES;
}
if ([self fjf_stringContainsEmoji:string]) {
return YES;
}
return NO;
}
三. ...全文
字符串響應(yīng)點(diǎn)擊事件
這里讓要...全文
字符串響應(yīng)點(diǎn)擊事件尊浓,一開(kāi)始很容易想到像TTTAttributedLabel
或者YYTLabel
等控件一樣,在-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
方法里面通過(guò)獲取到點(diǎn)擊位置纯衍,然后通過(guò)點(diǎn)擊位置栋齿,去獲取當(dāng)前點(diǎn)擊位置的字符串是否為...全文
,如果是就進(jìn)行事件的響應(yīng).
相關(guān)代碼:
#pragma mark - Public Methods
- (void)updateLabelWithExpandLabelStyle:(FJFExpandLabelStyle *)expandLabelStyle {
self.expandLabelStyle = expandLabelStyle;
NSAttributedString *tmpAttributedText = [FJFExpandLabelTool generateShowContentWithExpandLabelStyle:expandLabelStyle];
self.attributedText = tmpAttributedText;
CGFloat expandButtonX = expandLabelStyle.assignLineWidth;
if (expandLabelStyle.labelShowType == FJFExpandLabelShowTypeExpandAndPickup &&
expandLabelStyle.expandStatus) {
expandButtonX = expandLabelStyle.assignLineWidth - expandLabelStyle.expandLabelWidth;
if (expandButtonX < 0) {
expandButtonX = 0;
}
}
CGFloat expandButtonY = (self.frame.size.height - expandLabelStyle.assignLineHeight) / 2.0f + (expandLabelStyle.assignLineHeight - expandLabelStyle.expandLabelHeight);
CGFloat expandButtonWidth = expandLabelStyle.expandLabelWidth;
CGFloat expandButtonHeight = expandLabelStyle.expandLabelHeight;
self.expandFrame = CGRectMake(expandButtonX, expandButtonY, expandButtonWidth, expandButtonHeight);
}
#pragma mark - Override Method
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
CGPoint touchPoint = [[touches anyObject] locationInView:self];
if (CGRectContainsPoint(self.expandFrame, touchPoint)) {
[self.expandLabelStyle updateExpandStatus:!self.expandLabelStyle.expandStatus];
[self updateLabelWithExpandLabelStyle:self.expandLabelStyle];
if (self.expandLabelTapBlock) {
self.expandLabelTapBlock(self.expandLabelStyle.expandStatus);
}
}
}
四. FJFExpandLabel
最后對(duì)剛才的內(nèi)容進(jìn)行了整理和封裝,方便以后功能的復(fù)用和擴(kuò)展襟诸,于是有了FJFExpandLabel
瓦堵,這里FJFExpandLabel
繼承自UILabel
,方便替換歌亲,同時(shí)通過(guò)FJFExpandLabelStyle
配置參數(shù)來(lái)進(jìn)行參數(shù)的自我配置谷丸。
可配置參數(shù)如下:
// limitWidth 限制 寬度
@property (nonatomic, assign) CGFloat limitWidth;
// compareLineNum 比較行數(shù)
@property (nonatomic, assign) NSInteger compareLineNum;
// assignLineNum 指定截取行數(shù)
@property (nonatomic, assign) NSInteger assignLineNum;
// expandLabelWidth label 寬度
@property (nonatomic, assign) CGFloat expandLabelWidth;
// expandLabelHeight label 高度
@property (nonatomic, assign) CGFloat expandLabelHeight;
// labelShowType 顯示 類型
@property (nonatomic, assign) FJFExpandLabelShowType labelShowType;
// contentLabelStyle 文本 內(nèi)容 屬性
@property (nonatomic, strong) FJFLabelAttributeStyle *contentLabelStyle;
// expandLabelStyle 展開(kāi) 內(nèi)容 屬性
@property (nonatomic, strong) FJFLabelAttributeStyle *expandLabelStyle;
// pickupLabelStyle 收起 內(nèi)容 屬性
@property (nonatomic, strong) FJFLabelAttributeStyle *pickupLabelStyle;
// suffixLabelStyle 后綴(...) 內(nèi)容 屬性
@property (nonatomic, strong) FJFLabelAttributeStyle *suffixLabelStyle;
// assignLineWidth 指定行 字符串 寬度
@property (nonatomic, assign, readonly) CGFloat assignLineWidth;
// assignLineHeight 指定行 字符串 高度
@property (nonatomic, assign, readonly) CGFloat assignLineHeight;
// beyondLimit 是否 超過(guò) 限制
@property (nonatomic, assign, getter=isBeyondLimit, readonly) BOOL beyondLimit;
// expandStatus 展開(kāi)狀態(tài) 展開(kāi)/收起 (默認(rèn)收起狀態(tài))
@property (nonatomic, assign, getter=isExpandStatus, readonly) BOOL expandStatus;
這里有三種類型可以進(jìn)行設(shè)置:
- 一種是具有展開(kāi)和收起功能
- 一種是只有展開(kāi)的功能
- 一種是什么都沒(méi)有
具體配置代碼舉例如下:
@implementation FJFExpandLabelViewController
- (void)viewDidLoad {
[super viewDidLoad];
FJFExpandLabelStyle *tmpLabelStyle = [[FJFExpandLabelStyle alloc] init];
tmpLabelStyle.limitWidth = 280;
tmpLabelStyle.contentLabelStyle.labelText = @"??t??????x??丿??o wcqtx??a??xx??????e????mc??yt.m??????e????bcg??????e????j 6??????e????me??etm????aup \n Nh??n \n ?????????? r \n a??j m??gle?????? \n,????????????0bay,????z????[嗨],點(diǎn)擊[ https://pinyin.cn/e288503 ]查看表情";
tmpLabelStyle.compareLineNum = 3;
tmpLabelStyle.assignLineNum = 2;
tmpLabelStyle.labelShowType = FJFExpandLabelShowTypeExpandAndPickup;
FJFExpandLabel *tmpLabel = [[FJFExpandLabel alloc] initWithFrame:CGRectMake(60, 180, 280, 150)];
[tmpLabel updateLabelWithExpandLabelStyle:tmpLabelStyle];
tmpLabel.numberOfLines = 0;
[self.view addSubview:tmpLabel];
self.view.backgroundColor = [UIColor whiteColor];
}
@end
五. 遇到的問(wèn)題
這個(gè)功能的核心代碼就是通過(guò)CoreText
來(lái)獲取展示的每一行文本应结,其他的都是相關(guān)的邏輯性問(wèn)題刨疼,不過(guò)過(guò)程中遇到過(guò)一個(gè)坑,這里記錄下.
當(dāng)時(shí)通過(guò)CoreText
來(lái)獲取展示的每一行文本是直接從網(wǎng)上復(fù)制鹅龄、黏貼過(guò)來(lái)的揩慕,那段代碼里面設(shè)置富文本的字體是這樣寫的:
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:contentText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
[attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
CTFontRef myFont = CTFontCreateWithName((CFStringRef)([contentFont fontName]), [contentFont pointSize], NULL);
[attStr addAttribute:(NSString *)kCTFontAttributeName
value:(__bridge id)myFont
range:NSMakeRange(0, attStr.length)];
CFRelease(myFont);
通過(guò)函數(shù)CTFontCreateWithName
來(lái)創(chuàng)建CTFontRef格式的字體,然后設(shè)置到富文本中扮休,正常來(lái)說(shuō)CTFontRef
和UIFont
是可以相互轉(zhuǎn)換的迎卤,所以也沒(méi)有特別在意。
但其實(shí)這個(gè)函數(shù)CTFontCreateWithName
創(chuàng)建的字體和我們指定的字體是不一樣的玷坠。
比如說(shuō):
UIFont *contentFont = [UIFont systemFontOfSize:12];
CTFontRef myFont = CTFontCreateWithName((CFStringRef)([contentFont fontName]), [contentFont pointSize], NULL);
打印出兩個(gè)字體:
contentFont:
Printing description of contentFont:
<UICTFont: 0x7ff746003670> font-family: ".SFUI-Regular"; font-weight: normal; font-style: normal; font-size: 12.00pt
myFont:
Printing description of myFont:
<UICTFont: 0x7ff741404fa0> font-family: "Times New Roman"; font-weight: normal; font-style: normal; font-size: 12.00pt
而我其它地方富文本的字體屬性是直接通過(guò)NSFontAttributeName
來(lái)設(shè)置的,比如說(shuō):
[attributeString addAttribute:NSFontAttributeName value:contentLabelFont range:NSMakeRange(0, replyContent.length)];
因此就導(dǎo)致了蜗搔,計(jì)算的差異,這個(gè)問(wèn)題八堡,害我當(dāng)時(shí)找了挺久的樟凄,特意記錄一下。
推薦:
關(guān)于CoreText
的相關(guān)文章可以看下這位大神的幾篇文章兄渺,寫得特別清晰:
CoreText實(shí)現(xiàn)圖文混排
CoreText實(shí)現(xiàn)圖文混排之點(diǎn)擊事件
CoreText實(shí)現(xiàn)圖文混排之文字環(huán)繞及點(diǎn)擊算法
CoreText實(shí)現(xiàn)圖文混排之尺寸估算及文本選擇