Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

Objective-C
-(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;
}
Posted
Updated 10-Jan-15 23:48pm
v3

1 solution

Calculations for the heigth of the cell is best done in heightForRowAtIndexPath like here. If you have problem with an empty line an add a temporary blank on it.


An interesting article is also Auto Sizing Table Cells in iOS 8.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900