0

I have custom UITableViewCells that contain UITextViews. In previous versions of iOS I dynamically sized the table view cells like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Get the appropriate content string
    NSString *sectionKey = [self.orderedSectionKeys objectAtIndex:indexPath.section];
    NSDictionary *infoDictionary = [[self.tableViewData objectForKey:sectionKey] objectAtIndex:indexPath.row];
    NSString *textViewString = [infoDictionary objectForKey:@"description"];

    // Calculate the UITextView height
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, kInfoDefaultTableViewCellTextViewWidth, kInfoDefaultTableViewCellTextViewHeight)];        
    textView.font = [UIFont fontWithName:kInfoDefaultTableViewCellTextViewFont 
                                    size:kInfoDefaultTableViewCellTextViewFontSize];
    textView.text = textViewString;
    [textView layoutSubviews]; // Call this so that the content size is set

    CGFloat height = textView.contentSize.height;        
    height += kInfoDefaultTableViewCellHeightBuffer;

    return height;
}

This is still working for me in iOS 7, except when the textView string contains the new line characters: \n. Then contentSize.height is too small, like it is not adding the new lines but treating \n as characters. In the actual table view, the new lines are added.

Does anyone know how I can get the appropriate height with the new lines? I have tried the technique in this solution: https://stackoverflow.com/a/18818036/472344, but I am getting the same result as what I was using in the posted code.

Community
  • 1
  • 1
Darren
  • 10,091
  • 18
  • 65
  • 108
  • Try finding no of @"\n" in that string and multiply it with some constant height or something as you need ..! – Bala Sep 30 '13 at 06:58
  • http://stackoverflow.com/a/6111719/1059705 – Bala Sep 30 '13 at 07:02
  • Thanks... I've been playing around with my code, and I've gotten the solution in the answer that I linked to to work...I'm not sure why it wasn't working before. I imagine your solution could work as well, but it would be a little bit of a pain to implement. – Darren Oct 01 '13 at 03:23

1 Answers1

2

Add a KVO to the textView for the contentSize. Then reload the row, if the changes obtained.

  [textView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];

  - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    // Reload your exact row here
  }
Jayaprakash
  • 1,407
  • 1
  • 9
  • 19