将“…更多”添加到UILabel的末尾

我有一个UILabel ,在某些情况下,文本是更长的UILabel本身,所以我看到的文字为"bla bla bla..."我想添加...Read Morebutton文字在UILabel结束。 。

我已经阅读了一些post,但是他们提供的解决scheme对我来说并不好,例如:计算有多less个字符会进入UILabel ,但是使用每个字符的字体都有不同的宽度。

我怎么能做到这一点?

提前致谢!

所以这就是我所做的将更多…button添加到UITextViewUITextFieldUILabel

 - (void)addReadMoreStringToUILabel:(UILabel*)label { NSString *readMoreText = @" ...Read More"; NSInteger lengthForString = label.text.length; if (lengthForString >= 30) { NSInteger lengthForVisibleString = [self fitString:label.text intoLabel:label]; NSMutableString *mutableString = [[NSMutableString alloc] initWithString:label.text]; NSString *trimmedString = [mutableString stringByReplacingCharactersInRange:NSMakeRange(lengthForVisibleString, (label.text.length - lengthForVisibleString)) withString:@""]; NSInteger readMoreLength = readMoreText.length; NSString *trimmedForReadMore = [trimmedString stringByReplacingCharactersInRange:NSMakeRange((trimmedString.length - readMoreLength), readMoreLength) withString:@""]; NSMutableAttributedString *answerAttributed = [[NSMutableAttributedString alloc] initWithString:trimmedForReadMore attributes:@{ NSFontAttributeName : label.font }]; NSMutableAttributedString *readMoreAttributed = [[NSMutableAttributedString alloc] initWithString:readMoreText attributes:@{ NSFontAttributeName : Font(TWRegular, 12.), NSForegroundColorAttributeName : White }]; [answerAttributed appendAttributedString:readMoreAttributed]; label.attributedText = answerAttributed; UITagTapGestureRecognizer *readMoreGesture = [[UITagTapGestureRecognizer alloc] initWithTarget:self action:@selector(readMoreDidClickedGesture:)]; readMoreGesture.tag = 1; readMoreGesture.numberOfTapsRequired = 1; [label addGestureRecognizer:readMoreGesture]; label.userInteractionEnabled = YES; } else { NSLog(@"No need for 'Read More'..."); } } 

有一个使用fitString:intoLabel方法,可以在这里find。

至于UITagTapGestureRecognizer只是一个普通的UITapGestureRecognizer子类,带有一个名为tag的NSInteger属性。 我这样做,因为我想确定哪些Read More...被点击在我的情况下,我有不止一个在同一个UIViewController 。 您可以使用普通的UITapGestureRecognizer

请享用!

Tttattributed标签具有此function

https://github.com/TTTAttributedLabel/TTTAttributedLabel

您需要将“截断”标记设置为“阅读更多…”

看到

attributedTruncationToken

 var subTitleLabel = TTTAttributedLabel(frame : frame) self.addSubview(subTitleLabel) var trunc = NSMutableAttributedString(string: "...more") trunc.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: NSMakeRange(0, 7)) trunc.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: NSMakeRange(0, 7)) subTitleLabel.attributedTruncationToken = trunc subTitleLabel.numberOfLines = 1 subTitleLabel.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth 

Swift3(IOS 10.3)

阅读更多的标签没有采取行动结束

 extension UILabel { func addTrailing(with trailingText: String, moreText: String, moreTextFont: UIFont, moreTextColor: UIColor) { let readMoreText: String = trailingText + moreText let lengthForVisibleString: Int = self.vissibleTextLength() let mutableString: String = self.text! let trimmedString: String? = (mutableString as NSString).replacingCharacters(in: NSRange(location: lengthForVisibleString, length: ((self.text?.characters.count)! - lengthForVisibleString)), with: "") let readMoreLength: Int = (readMoreText.characters.count) let trimmedForReadMore: String = (trimmedString! as NSString).replacingCharacters(in: NSRange(location: ((trimmedString?.characters.count ?? 0) - readMoreLength), length: readMoreLength), with: "") + trailingText let answerAttributed = NSMutableAttributedString(string: trimmedForReadMore, attributes: [NSFontAttributeName: self.font]) let readMoreAttributed = NSMutableAttributedString(string: moreText, attributes: [NSFontAttributeName: moreTextFont, NSForegroundColorAttributeName: moreTextColor]) answerAttributed.append(readMoreAttributed) self.attributedText = answerAttributed } func vissibleTextLength() -> Int { let font: UIFont = self.font let mode: NSLineBreakMode = self.lineBreakMode let labelWidth: CGFloat = self.frame.size.width let labelHeight: CGFloat = self.frame.size.height let sizeConstraint = CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude) let attributes: [AnyHashable: Any] = [NSFontAttributeName: font] let attributedText = NSAttributedString(string: self.text!, attributes: attributes as? [String : Any]) let boundingRect: CGRect = attributedText.boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, context: nil) if boundingRect.size.height > labelHeight { var index: Int = 0 var prev: Int = 0 let characterSet = CharacterSet.whitespacesAndNewlines repeat { prev = index if mode == NSLineBreakMode.byCharWrapping { index += 1 } else { index = (self.text! as NSString).rangeOfCharacter(from: characterSet, options: [], range: NSRange(location: index + 1, length: self.text!.characters.count - index - 1)).location } } while index != NSNotFound && index < self.text!.characters.count && (self.text! as NSString).substring(to: index).boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, attributes: attributes as? [String : Any], context: nil).size.height <= labelHeight return prev } return self.text!.characters.count } } 

用法

 let readmoreFont = UIFont(name: "Helvetica-Oblique", size: 11.0) let readmoreFontColor = UIColor.blue DispatchQueue.main.async { self.yourLabel.addTrailing(with: "... ", moreText: "Readmore", moreTextFont: readmoreFont!, moreTextColor: readmoreFontColor) } 

结果

Readmore标签输出

Readmore不包含操作

我的解决scheme是,我创build一个UIButton (名称阅读更多)在右下方和UILabel下面。 之后,我检查UILabel被截断或不显示或隐藏UIButton

 CGSize sizeOfText = [self.label.text boundingRectWithSize: CGSizeMake(self.label.intrinsicContentSize.width, CGFLOAT_MAX) options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes: [NSDictionary dictionaryWithObject:self.label.font forKey:NSFontAttributeName] context: nil].size; if (self.label.intrinsicContentSize.height < ceilf(sizeOfText.height)) { // label is truncated self.readmoreButton.hidden = NO; // show Read more button }else{ self.readmoreButton.hidden = YES; } 

=== Swift 3版本

 let textheight = self.label.text?.height(withConstrainedWidth: self.label.frame.width, font: self.label.font) if self.label.intrinsicContentSize.height < textheight! { self.readmoreButton.isHidden = false }else{ self.readmoreButton.isHidden = true } 

添加这个扩展名:

 extension String { func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return boundingBox.height } 

}

希望这个帮助

你可以尝试第三个库ExpandableLable

将UILabel的自定义类设置为ExpandableLabel并设置所需的行数和折叠文本:

 expandableLabel.numberOfLines = 5 expandableLabel.collapsedAttributedLink = NSAttributedString(string: "more") expandableLabel.ellipsis = NSAttributedString(string: "...") // update label expand or collapse state expandableLabel.collapsed = true 

您可能需要设置一个delegate ,以便在链接被触摸的情况下得到通知。

使用方法- boundingRectWithSize:options:attributes:context:并将NSFontAttributeName的字体作为NSFontAttributeName传递给您需要的正确rect。

从那你需要检查它是否比你的标签边界减去偏移量大。 只有如果是的话,你需要修剪你的文本,并在最后显示Read More

你知道UILabel没有触摸动作吗? 所以你不能碰'如果在UILabel中的整个文本阅读更多'。

注:我的解决scheme是,添加一个清晰的UILabel背景button结束。

这个方法是非常有用的showAll和showAll上下箭头图像:添加标签上的tapgesture

  viewcontroller.h @property (nonatomic,assign) BOOL isReadable; viewcontrollr.m #pragma mark :- Tap Gesture View All -(void)readMoreDidClickedGesture :(UITapGestureRecognizer *)objTapGesture{ UILabel * lblDesc = (UILabel *)[objTapGesture view]; NSLog(@"%@",lblDesc.text); if (self.isReadable == false) { [self setIsReadable:YES]; lblDesc.text = readmoreText; readMoreHeight = [self getLabelHeight:lblDesc]; } else{ readMoreHeight = 30.0; [self setIsReadable:NO]; } } - (void)addReadMoreStringToUILabel:(UILabel*)label isReaded:(BOOL)isReaded { NSString *readMoreText = (isReaded == false) ? @"...Show All " : @"Show Less "; NSInteger lengthForString = label.text.length; if (lengthForString >= 30) { NSInteger lengthForVisibleString = [self getLabelHeight:label];//[self fitString:label.text intoLabel:label]; NSMutableString *mutableString = [[NSMutableString alloc] initWithString:label.text]; readmoreText = mutableString; NSString *trimmedString = [mutableString stringByReplacingCharactersInRange:NSMakeRange(lengthForVisibleString, (label.text.length - lengthForVisibleString)) withString:@""]; NSInteger readMoreLength = readMoreText.length; NSString *trimmedForReadMore = [trimmedString stringByReplacingCharactersInRange:NSMakeRange((trimmedString.length - readMoreLength), readMoreLength) withString:@""]; NSMutableAttributedString *answerAttributed = [[NSMutableAttributedString alloc] initWithString:trimmedForReadMore attributes:@{ NSFontAttributeName : label.font }]; NSMutableAttributedString *readMoreAttributed = [[NSMutableAttributedString alloc] initWithString:readMoreText attributes:@{ NSFontAttributeName :label.font, NSForegroundColorAttributeName :[UIColor orangeColor] }]; if (isReaded == false){ [readMoreAttributed addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(3, 8)]; NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init]; UIImageView *imgDown = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 25, 25)]; imgDown.image = [UIImage imageNamed:@"searchFilterArrow1"]; imgDown.image = [imgDown.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [imgDown setTintColor:[UIColor orangeColor]]; textAttachment.image = imgDown.image; NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment]; [readMoreAttributed replaceCharactersInRange:NSMakeRange(12, 1) withAttributedString:attrStringWithImage]; } else{ [readMoreAttributed addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(1, 9)]; NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init]; UIImageView *imgup = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 25, 25)]; imgup.image = [UIImage imageNamed:@"searchFilterArrow2"]; imgup.image = [imgup.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [imgup setTintColor:[UIColor orangeColor]]; textAttachment.image = imgup.image; NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment]; [readMoreAttributed replaceCharactersInRange:NSMakeRange(11, 1) withAttributedString:attrStringWithImage]; } [answerAttributed appendAttributedString:readMoreAttributed]; label.attributedText = answerAttributed; UITapGestureRecognizer *readMoreGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(readMoreDidClickedGesture:)]; readMoreGesture.numberOfTapsRequired = 1; [label addGestureRecognizer:readMoreGesture]; label.userInteractionEnabled = YES; } else { NSLog(@"No need for 'Read More'..."); } }