Resize the UITextView to the size of its text and reduce the size if it is larger than the height

I am trying to make a table view similar to apps like facebook where it shows text messages and if the message is too big it will reduce the size and add a More button. I have looked at many different solutions for resizing UITextViews to the height of their text, however none of them solve my problem. My problem only exists with large posts. When I have a large post, my function that returns the height of the textView should return the maxHeight of the messages before expanding. This part works. However, when I click the Read More button, I have a huge amount of white space at the bottom of the full text. Here is my code:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
     return heightForTextOfRow(indexPath.row) + PostCell.additionalVertSpaceNeeded
}

func heightForTextOfRow(row: Int) -> CGFloat {
     var textView = UITextView(frame: CGRectMake(0, 0, prototypeTextViewWidth, CGFloat.max))
     let post = data[row]

     textView.text = (post.postText as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
     textView.textContainer.lineFragmentPadding = 0
     textView.textContainerInset = UIEdgeInsetsZero
     textView.font = PostCell.textViewFont
     textView.frame.size = textView.sizeThatFits(CGSizeMake(prototypeTextViewWidth, CGFloat.max))
     if textView.frame.size.height > maxHeight && !post.seeMore {
         return maxHeight
     } else {
         return textView.frame.size.height
     }

}

      

Some code explanations:

  • data is an array of posts (the only thing relevant to the Post class in this case is that it has a postText and seeMore property.)
  • PostCell.textViewFont is a constant in one of my classes, which returns the font that I am using (system font size 13)
  • PostCell.additionalVertSpaceNeeded is a constant that returns the height of all other elements in my prototype cell except for UITextView
  • prototypeTextViewWidth is defined as tableView.frame.width - 16 (16 is the value of the fields added together)
  • maxHeight is the maximum height of a post that does not want to show the full post (currently defined as tableView.frame.height * 0.625 - PostCell.additionalVertSpaceNeeded)
  • seeMore - the Bool Post property that tells whether to show or not show the full post or show only part of the post (true shows the full post, false shows the maxHeight message)

Any help would be appreciated ... I have tried many solutions for resizing UITextView and all have the same problem. Thanks in advance!

+3


source to share





All Articles