UILabel 末尾显示更多

xiaoxiao2021-02-28  113

UILabel 末尾要出现 “…更多 ”

效果如下:

普通的做法没什么思路。 后面想到了label进行文字分割

//得到label 每一行的文字 - (NSArray *)getSeparatedLinesFromLabel:(UILabel *)label { [self layoutIfNeeded]; NSString *text = [label text]; UIFont *font = [label font]; CGRect rect = [label frame]; 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]; } return (NSArray *)linesArray; }

由于需求只要求最多显示两行 调用如下:

NSArray *array = [self getSeparatedLinesFromLabel:self.contentLabel]; if (array.count > 0) { self.contentLabel.text = array[0]; NSString *strs; if (IsStrEmpty(exploreModel.mdq_context)) { //默认字典文案 strs = [[DBHelpTool getTanSuoText] substringFromIndex:self.contentLabel.text.length]; }else { strs = [exploreModel.mdq_context substringFromIndex:self.contentLabel.text.length]; } NSAttributedString *attr = [[NSAttributedString alloc] initWithString:strs]; self.contentLabelButtom.attributedText = attr; if (array.count > 1) { self.moreLabel.hidden = NO; }else { self.moreLabel.hidden = YES; } }else { self.contentLabel.text = exploreModel.mdq_context; self.contentLabelButtom.text = @""; self.moreLabel.hidden = YES; }
转载请注明原文地址: https://www.6miu.com/read-40209.html

最新回复(0)