Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand UITextView height (read more effect) in UITableViewCell

I'm trying to expand UITextView with animation, when user tap read more button bellow it.

enter image description here

I've tried a lot of approaches and come up with almost working solution:

func readMore() {
    self.tableView.beginUpdates()
    cell.descTextViewHeightConstraint.constant = cell.descTextView.expectedHeight()
    self.tableView.endUpdates()
}

UItextView+Height

extension UITextView {
    func expectedHeight() -> CGFloat {
        let textView: UITextView = UITextView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
        textView.font = self.font
        textView.text = self.text
        textView.sizeToFit()
        return textView.frame.height
    }
}

This solution works, but has one sideeffect - when the animation finishes, some of elements in the UITableViewCell are hidden (title label).

I've also tried to call tableView.reloadData() when the animation finishes, which works, but sometimes has sideeffects as well.

like image 503
filip.karas Avatar asked Oct 12 '17 07:10

filip.karas


1 Answers

Why don't you "play" with the numberOfLines property?

For a project I did something similar like this (there was also a UIImage arrow that made a rotation...). Everything was inside a custom cell class:

func setExpanded(_ isExpanded: Bool) {
    if isExpanded {
        lblFullDescription.numberOfLines = 0
        UIView.animate(withDuration: Constants.NavigationBar.AnimationTime, animations: { [weak self] in
            self?.imgArrow.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
        })

    } else {
        lblFullDescription.numberOfLines = 2
        UIView.animate(withDuration: Constants.NavigationBar.AnimationTime, animations: { [weak self] in
            self?.imgArrow.transform = CGAffineTransform(rotationAngle: CGFloat(0))
        })
    }
}

And add this in the ViewController that holds the UITableView:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 42
like image 200
DungeonDev Avatar answered Oct 18 '22 12:10

DungeonDev