如何使用 Swift 3 在 Read More/Less 中设置标签高度以进行自动调整? [英] How to set label height for auto adjust in Read More/Less with Swift 3?

查看:31
本文介绍了如何使用 Swift 3 在 Read More/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

    }

}


我还在属性检查器中设置了标签自动换行".
问题是,当我在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆