0

Im trying to implement "show more/show less" functionality to my UILabel in the tableView cell. I`ve tried searching the solution on the web, but they all seem to be outdated.

The caption text should have 2 lines and if its more than that it will expand to the full text

 lazy var captionText: UILabel = {
        let lbl = UILabel()
        lbl.numberOfLines = 2
        lbl.lineBreakMode = .byWordWrapping
        return lbl
    }()

func setupUI(viewModel: FeedModel) {

        captionText.text = viewModel.postDescription
}

I`d love the final result look like this:

Expandable UILabel sample

Expanded UILabel sample

Russ
  • 53
  • 1
  • 9
  • Does this answer your question? [iOS: UILabel with a "Show more" button](https://stackoverflow.com/questions/26294851/ios-uilabel-with-a-show-more-button) – CSmith Jun 16 '21 at 10:51
  • @CSmith unfortunately no, the pod suggested is written in objective-c. I am using swift 5 – Russ Jun 16 '21 at 10:53
  • Does this answer your question? [Add "...Read More" to the end of UILabel](https://stackoverflow.com/questions/32309247/add-read-more-to-the-end-of-uilabel) – Tushar Sharma Jun 16 '21 at 11:07
  • In case you are trying it on a test project, you might want to experiment with [UILabel.showsExpansionTextWhenTruncated](https://developer.apple.com/documentation/uikit/uilabel/3750862-showsexpansiontextwhentruncated) – Tarun Tyagi Jun 16 '21 at 11:50

1 Answers1

6

You can try this 3rd party in Swift: https://github.com/apploft/ExpandableLabel

Set your label UILabel to ExpandableLabel and set the desired properties:

yourLabel.numberOfLines = 2
yourLabel.collapsed = true
yourLabel.collapsedAttributedLink = NSAttributedString(string: "See more")
yourLabel.ellipsis = NSAttributedString(string: "...")

It's has ExpandableLabelDelegate in case you want to get notification when the link has been touched.

Dharman
  • 30,962
  • 25
  • 85
  • 135
AnLT
  • 569
  • 8
  • 22