How to set label height for auto-tuning in Read More / Less with Swift 3?

I would like to create a paragraph using 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 word wrap label to Attribute Inspector.
The problem is that when I add "NSLineBreakMode.byTruncatingHead" in the "Read less" part, all texts are fully displayed. But some words in these places inside the text disappear.

So, I delete this code and run the application. At that time, the texts are not shown in full and show only half. I tried to solve this problem all day.
I do not want to use any other library.
Can anyone help me?

0
2

lblReviewHeight, numberOfLines , numberOfLines = 0, numberOfLines .

+1

,

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)
0

Source: https://habr.com/ru/post/1660652/


All Articles