SagittariusA
SagittariusA

Reputation: 5427

Swift: how to adapt UITableViewCell height to a UITextView inside it

Which is the simplest way both to adapt UITextView height to its content and then to adapt a UITableViewCell height, which acts as a container, to the same height of that UITextView?

Upvotes: 1

Views: 615

Answers (2)

Lucho
Lucho

Reputation: 1044

To calculate the height of your textview, i think you need to know the height of the text. So on your heightForRowAtIndexPath delegate method, calculate the text height and return it using this:

func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
    let constraintRect = CGSize(width: width, height: CGFloat.max)

    let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

    return boundingBox.height
}

You need to set the textview constrains, bottom, top, leading and trailing to 0, so they adjust to the size of the cell. The code was taken from here.

Upvotes: 2

Ro22e0
Ro22e0

Reputation: 394

Set your UITextView number of line to 0. In the viewDidLoad of your Controller that contains the tableView use :

 tableView.estimatedRowHeight = 55.0
 tableView.rowHeight = UITableViewAutomaticDimension

Upvotes: 2

Related Questions