0

UITextViews を含むカスタム UITableViewCells があります。以前のバージョンの iOS では、次のようにテーブル ビュー セルのサイズを動的に変更しました。

- (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;
}

textView 文字列に改行文字 \n が含まれている場合を除いて、これは iOS 7 でも機能します。次に、 contentSize.height が小さすぎます。新しい行を追加するのではなく、 \n を文字として扱っているようです。実際のテーブル ビューでは、新しい行が追加されます。

新しい行で適切な高さを取得する方法を知っている人はいますか? https://stackoverflow.com/a/18818036/472344のソリューションでこの手法を試しましたが、投稿されたコードで使用していたものと同じ結果が得られます。

4

1 に答える 1

2

contentSize の textView に KVO を追加します。変更が取得された場合は、行をリロードします。

  [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
  }
于 2013-10-29T14:23:48.817 に答える