Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an expandable text field/label in swift?

Tags:

xcode

ios

swift

I need to figure out how to program something like this: enter image description here

The text expands as the user clicks the down button and fold back to the short version after clicking up. Are there any libraries I could study? I am a beginner in programming and just need advice on how to approach this task, what guides to study and so on.

like image 710
Anton Platonov Avatar asked Dec 02 '22 12:12

Anton Platonov


2 Answers

All you have to do is initially set the UILabel to have a numberOfLines of lets say 7 and line break mode to be .byTruncatingTail.

Then on button click simply change the numberOfLines to 0 and line break mode to be .byWordWrapping. Then when you wish to hide the text, just press the button and set the UILabel to its initial values.

like image 114
Rikh Avatar answered Dec 05 '22 10:12

Rikh


To solve this issue read about AutoLayout. This is small example how it is possible to do.

This is coding part. This class contain IBOutlet for the height of the UITextView and button action.

class ViewController: UIViewController {

    let defaultHeight = 128
    let expectedHeight = 600
    var state: Bool = false

    @IBOutlet weak var height: NSLayoutConstraint!

    @IBAction func showAction(_ sender: Any) {
        UIView.animate(withDuration: 0.3, animations: {
                self.state = !self.state
                self.height.constant = CGFloat(self.state ? self.expectedHeight: self.defaultHeight)
                self.view.layoutIfNeeded()
        })
    }
}

This is from storyboard.

enter image description here

like image 39
Oleg Gordiichuk Avatar answered Dec 05 '22 10:12

Oleg Gordiichuk