如何使用Swift 3在Read More / Less中设置自动调整的标签高度? [英] How to set label height for auto adjust in Read More/Less with Swift 3?
问题描述
我想在最后创建带有Read More / Read Less的段落。这是我的代码;
I would like to create the paragraph with Read More/Read Less at the end.
Here are my codes;
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
}
}
我还在Attributes Inspector中设置了自动换行标签。
问题是当我在Read Less部分中添加NSLineBreakMode.byTruncatingHead时,所有文本都会完整显示。但是,文本中那些地方的一些词语消失了。
I also set the label "Word wrap" in Attributes Inspector.
The problem is that when I add "NSLineBreakMode.byTruncatingHead" in Read Less part, all the texts show completely. But, some words in those places inside text disappear.
因此,我删除了该代码并运行该应用程序。那时,文本没有完全显示,只显示了一半。我一直在努力解决这个问题。
我不想使用任何其他库。
有人可以帮帮我吗?
So, I remove that code and run the app. At that time, texts are not shown completely and only show half. I've been trying to solve this problem the whole day.
I don't want to use any other library.
Could anyone help me please?
推荐答案
删除约束 lblReviewHeight
,然后尝试使用 numberOfLines
控制文本布局,如果你想要显示所有描述集 numberOfLines = 0
,否则将 numberOfLines
设置为您想要的行。
Remove constraint lblReviewHeight
, then just try to use numberOfLines
control your text layout, if your want show all description set numberOfLines = 0
, otherwise set numberOfLines
to the line you want.
这篇关于如何使用Swift 3在Read More / Less中设置自动调整的标签高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!