如何在最后使用Read More / Read Less创建段落(标签中)?

时间:2017-11-18 10:43:10

标签: iphone swift3

我想在最后用Read More / Read Less创建段落(标签中)。我是iPhone应用程序开发的初学者。

这是我的代码...... 我在else条件中遇到错误。该错误是" NSLayoutConstraint类型的值"没有会员' font'"在lbl.contant = getheight ....

@IBOutlet weak var lbl: NSLayoutConstraint!

@IBOutlet weak var btn: UIButton!        

var isLabelAtMaxHeight = false

@IBAction func ButtonAction(_ sender: Any) {
    if isLabelAtMaxHeight {
        btn.setTitle("Read more", for: .normal)
        isLabelAtMaxHeight = false
        lbl.constant = 70
    }
    else {
        btn.setTitle("Read less", for: .normal)
        isLabelAtMaxHeight = true
        lbl.constant = getHeightOfLabel(text:"Isn't it? How to do? I'm sorry I don't know how to solve this exactly. :( – May Phyu Feb 20 at 11:16 No, i dont mean like that. When you set text to label then U have to find height of label then assign that height to label with setting property number of lines = 0 – Jitendra Modi Feb 20 at 11:31" , width:
            view.bounds.width, font: lbl.font)
    }
}



func getHeightOfLabel(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()
    return lbl.frame.size.height
} 

1 个答案:

答案 0 :(得分:0)

  • 为paragraphLabel创建高度约束的出口。
  • 设置"阅读更多"的顶部布局按钮到paragraphLabel。
  • 点击"了解更多"按钮增加高度约束常数,点击"少阅读"减少高度约束常数。

    @IBOutlet weak var btn: UIButton!
    @IBOutlet weak var yourParagraphLabel: UILabel!
    @IBOutlet weak var lblHeight: NSLayoutConstraint!
    
    var isLabelAtMaxHeight = false
    
    @IBAction func btnAction(_ sender: Any) {
        if isLabelAtMaxHeight {
        btn.setTitle("Read more", for: .normal)
        isLabelAtMaxHeight = false
        lblHeight.constant = 70
    }
    else {
       btn.setTitle("Read less", for: .normal)
       isLabelAtMaxHeight = true
       lblHeight.constant = getHeightOfLabel(text: yourParagraphText, width: 
       view.bounds.width, font: yourParagraphLabel.font)
    }
    }
    

    获取文字的高度

    func getHeightOfLabel(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()
       return lbl.frame.size.height
    }