Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

ios - Read More/Less with Swift 3

I want to add "Read more" at the end of the paragraph. When I click on the "Read more" text, it should be expand and display "Less" at the end. The texts will be collapsed when click on "Less" text.

enter image description here
I find many sample work in google. But, I don't understand clearly and most projects are implemented with Objective-C. I also find it in youtube.
I would like know very sample code to implement this with Swift 3.
Can I implement without using any additional library?
Please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • Create an outlet for height constraint of your messageLabel
  • Set top layout of your "Read more" button to messageLabel
  • On clicking "Read more" button increase height constraint constant, on clicking "Read less" decrease height constraint constant.

    @IBOutlet weak var btn: UIButton!
    
    @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 = getLabelHeight(text: yourSummaryText, width: view.bounds.width, font: yourSummaryLabel.font)
        }
    }
    

Get height of a text

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

        return lbl.frame.size.height
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...