How to Resize UITableViewCell by Size of a UITextView Inside it?

UITableView and UITextView

For learning how to manage UITableViewCell Height according to size of UITextView’s text first you have the basic idea about what UITextView and UITableViewCell.

UITableView: UITextView supports the display of text using and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document. For more Deails see here https://developer.apple.com/documentation/uikit/uitextview

UITableView: UITableView is used to display the elements in row with scrolling. It displays elements in list in single column and it allows only vertical scrolling. For more Deails see here https://developer.apple.com/documentation/uikit/uitableview

Steps for UITableViewCell Resize and UITextView size

Resize of UITableViewCell according to size of UITableView in it

To manage Height of UITableViewCell according to UITableView follow these steps

STEP1: First Declare UITableViewCell variable

YourCustomCell *customCell;

STEP2: Initialize that cell you declared.

customCell = . [[YourCustomCell alloc] init];

STEP3: create a new method in your YourCustomCell.m file

- (CGFloat)getCellHeight{
textView.text = @"Your Text";
CGSize maximumTextViewSize = CGSizeMake(textView.frame.size.width, CGFLOAT_MAX);
NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
NSDictionary *attr = @{NSFontAttributeName: [your font and font size]};
CGRect textViewBounds = [textView.text boundingRectWithSize:maximumTextViewSize
options:options
attributes:attr
context:nil];
CGFloat height = ceilf(textViewBounds.size.height);
return height;
}

STEP4: in method of UITableView Delegates

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return [customCell getCellHeight];
}

Leave a Comment