Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I had the same issue for an iPad app and came up with another solution without having calculating the height of the text itself.</p> <p>First create a custom UITableViewCell in IB with an UITextField placed in the cell's contentView. It's important to set the text view's <strong>scrollEnabled</strong> to NO and the <strong>autoresizingMask</strong> to flexibleWidth and flexibleHeight.</p> <hr> <p>In the ViewController implement the text view's delegate method <strong>-textViewDidChanged:</strong> as followed, where <strong>textHeight</strong> is a instance variable with type CGFloat and <strong>-tableViewNeedsToUpdateHeight</strong> is a custom method we will define in the next step.</p> <pre><code>- (void)textViewDidChange:(UITextView *)textView { CGFloat newTextHeight = [textView contentSize].height; if (newTextHeight != textHeight) { textHeight = newTextHeight; [self tableViewNeedsToUpdateHeight]; } } </code></pre> <hr> <p>The method <strong>-tableViewNeedsToUpdateHeight</strong> calls the table view's <strong>beginUpdates</strong> and <strong>endUpdates</strong>, so the table view itself will call the <strong>-tableView:heightForRowAtIndexPath:</strong> delegate method.</p> <pre><code>- (void)tableViewNeedsToUpdateHeight { BOOL animationsEnabled = [UIView areAnimationsEnabled]; [UIView setAnimationsEnabled:NO]; [table beginUpdates]; [table endUpdates]; [UIView setAnimationsEnabled:animationsEnabled]; } </code></pre> <hr> <p>In the table view's <strong>-tableView:heightForRowAtIndexPath:</strong> delegate method we need to calculate the new height for the text view's cell based on the <strong>textHeight</strong>. </p> <p>First we need to resize the text view cells height to the maximum available height (after subtracting the height of all other cells in the table view). Then we check if the textHeight is bigger than the calculated height.</p> <pre><code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { CGFloat heightForRow = 44.0; if ([indexPath row] == kRowWithTextViewEmbedded) { CGFloat tableViewHeight = [tableView bounds].size.height; heightForRow = tableViewHeight - ((kYourTableViewsNumberOfRows - 1) * heightForRow); if (heightForRow &lt; textHeight) { heightForRow = textHeight; } } return heightForRow; } </code></pre> <hr> <p>For a better user experience set the table view's content insets for bottom to e.g. 50.0. </p> <p>I've tested it on the iPad with iOS 4.2.1 and works as expected.</p> <p>Florian</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload