1

I am aware that this question has been asked, but none of the answers have worked for me. I'm trying to implement a comments View controller, similar to what you can see in Instagram, where the size of the tableView cell depends on the size of the comment. So I though I would get the necessary height to display the whole comment in textView without scrolling, adjust the textView, then use it to set the heightForRowAtIndexPath appropriately, before finally reloading the table. However, I can't even get to resize the textView, I have tested a certain number of answers and still the textView won't budge.

sizeToFit and pinning to superview didn't work.

Any ideas on how I can do this?

Thanks for your help

Charles Panel
  • 255
  • 2
  • 10

1 Answers1

2

Best way to approach this is to calculate the size of your tableviewcell based on the size of the string you're wanting to display.

Don't use the size of the textView because it doesn't really know its contents until it gets displayed.

Try this to get the height of the string:

func calculateHeightForString(inString:String) -> CGFloat
{
    var messageString = inString
    var attributes = [UIFont(): UIFont.systemFontOfSize(15.0)]
    var attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes)
    var rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(300.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )
    var requredSize:CGRect = rect
    return requredSize.height  //to include button's in your tableview
 }

taken from the top answer here: Dynamically size uitableViewCell according to UILabel (With paragraph spacing)

Then all you need to do is add the padding to that height result for your tableviewcell.

As long as your textview is setup with the correct constraints by pinning it to all 4 sides of the tableViewCells content view, everything should work out fine.

Community
  • 1
  • 1
Beau Nouvelle
  • 6,962
  • 3
  • 39
  • 54