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
}
}
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?
to calculate text height by font and width you can use this extension
then call it
Remove constraint
lblReviewHeight
, then just try to usenumberOfLines
control your text layout, if your want show all description setnumberOfLines = 0
, otherwise setnumberOfLines
to the line you want.