我有包含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;
}
这在 iOS 7 中仍然对我有用,除非 textView 字符串包含换行符:。 然后 contentSize.height 太小,就像它没有添加新行而是将 视为字符一样。在实际表视图中,将添加新行。
有谁知道我如何用新线获得合适的高度?我已经尝试了此解决方案中的技术:https://stackoverflow.com/a/18818036/472344,但我得到的结果与我在发布的代码中使用的结果相同。
将 KVO 添加到 contentSize 的文本视图中。然后重新加载该行(如果获得了更改)。
[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
}