How to set label height for auto adjust in Read Mo

2020-02-16 04:05发布

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?

2条回答
劫难
2楼-- · 2020-02-16 04:34

to calculate text height by font and width you can use this extension

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
}
}

then call it

let width = 290.0
let textSize = UIFont.systemFont(ofSize: 15).sizeOfString("text", constrainedToWidth: width)
查看更多
再贱就再见
3楼-- · 2020-02-16 04:39

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.

查看更多
登录 后发表回答