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
?
Asked
Active
Viewed 610 times
1

rmaddy
- 314,917
- 42
- 532
- 579

SagittariusA
- 5,289
- 15
- 73
- 127
2 Answers
2
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

Ro22e0
- 364
- 1
- 10
-
If your text is large, you may have to use a higher number than 55 for the `estimatedRowHeight`. – koen Mar 16 '16 at 16:35
-
Yeah this value depends of what you have in your UITableViewCell – Ro22e0 Mar 16 '16 at 16:36
2
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.