如何设置标签高度自动调整阅读更多/更less使用Swift 3?

我想在最后创build带有Read More / Read Less的段落。
这是我的代码;

func getLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat { let lbl = UILabel(frame: .zero) lbl.frame.size.width = width lbl.font = font lbl.numberOfLines = 0 lbl.text = text lbl.sizeToFit() lbl.adjustsFontSizeToFitWidth = true return lbl.frame.size.height } 

  @IBAction func btnReadMore(_ sender: Any) { if isLabelAtMaxHeight { btnReadmore.setTitle(NSLocalizedString("Read more", comment: ""), for: .normal) btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13) isLabelAtMaxHeight = false lblReviewHeight.constant = 29 lblReview.font = UIFont (name: "Tharlon", size: 13) } else { btnReadmore.setTitle(NSLocalizedString("Read less", comment: ""), for: .normal) btnReadmore.titleLabel!.font = UIFont (name: "Tharlon", size: 13) isLabelAtMaxHeight = true lblReviewHeight.constant = getLabelHeight(text: lblReview.text!, width: view.bounds.width, font: lblReview.font) lblReview.font = UIFont (name: "Tharlon", size: 13) lblReview.lineBreakMode = NSLineBreakMode.byTruncatingHead } } 

我还在属性检查器中设置了标签“自动换行”。
问题是,当我在Read Less部分中添加“NSLineBreakMode.byTruncatingHead”时,所有文本都完全显示。 但是,文字内部的某些字词消失了。

所以,我删除了该代码并运行该应用程序。 当时,文本没有完整显示,只显示一半。 我一整天都在试图解决这个问题。
我不想使用任何其他库。
任何人都可以帮我吗?

删除约束lblReviewHeight ,然后试着用numberOfLines控制你的文本布局,如果你想显示所有的描述设置numberOfLines = 0 ,否则将numberOfLines设置为你想要的行。

通过字体和宽度来计算文本高度,你可以使用这个扩展名

 extension UIFont { func sizeOfString (_ string: String, constrainedToWidth width: CGFloat) -> CGSize { return NSString(string: string).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: self], context: nil).size } } 

然后调用它

 let width = 290.0 let textSize = UIFont.systemFont(ofSize: 15).sizeOfString("text", constrainedToWidth: width)