如何使用Swift 3在Read More / Less中设置自动调整的标签高度?

时间:2017-07-07 09:14:34

标签: ios swift3 uilabel nsattributedstring

我想在最后创建带有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

    }

}


我还在Attributes Inspector中设置了标签“Word wrap”。
问题是当我在Read Less部分中添加“NSLineBreakMode.byTruncatingHead”时,所有文本都会完整显示。但是,文本中那些地方的一些词语消失了。

因此,我删除了该代码并运行该应用程序。那时,文本没有完全显示,只显示了一半。我一直在努力解决这个问题。
我不想使用任何其他库。
有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

按字体和宽度计算文字高度,您可以使用此扩展程序

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)