I have a UITextView in a UITableViewCell. I added auto constraints to the textView. I want the textView to dynamically size itself when the user enters text, and I want the cell to dynamically size itself according to the textView.
When I run the code bellow, what happens is:
1 - At first the textViews height is really small as shown:
Picture1
2 - Next, when I insert text without making a new line, this is what happens:
Picture2
3 - When I make a new line, I don't see it until I create a new line and only after I enter text do I see it:
Picture3
I only see 'how' once I enter text on the next line which I can't see (yet).
4 - The trick around issue #3 is if I click on a line that I can totally see (meaning not the 2 last lines) and I create a new line from there. Only if I do it that way will it behave normally (with hiding the last line).
Picture4
Please don't be too harsh cause I'm a beginner.
Thanks
Here is my code:
-(void)viewDidLoad
{
tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = 44;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if (textView == myTextView)
{
[self textViewFitToContent:myTextView];
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
return YES;
}
- (void)textViewFitToContent:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
textView.scrollEnabled = NO;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 1 && indexPath.row == 0) {
return myTextview.frame.size.height + 40;
}
return 44;
}