【问题标题】:Calculating UITextView content size height when content has "\n" characters, in iOS 7在 iOS 7 中,当内容具有“\n”字符时计算 UITextView 内容大小高度
【发布时间】:2013-09-29 23:40:28
【问题描述】:

我有包含 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 字符串包含换行符:\n。然后 contentSize.height 太小了,就像它没有添加新行而是将 \n 视为字符。在实际的表格视图中,添加了新行。

有谁知道我怎样才能用新线获得合适的高度?我已经在这个解决方案中尝试过该技术:https://stackoverflow.com/a/18818036/472344,但我得到的结果与我在发布的代码中使用的结果相同。

【问题讨论】:

  • 尝试在该字符串中找到没有@"\n" 并将其乘以某个恒定高度或您需要的其他东西..!
  • 谢谢...我一直在玩弄我的代码,并且我已经在与工作相关的答案中找到了解决方案...我不确定为什么会这样以前没有工作。我想你的解决方案也可以工作,但实施起来会有点痛苦。

标签: ios uitableview uitextview ios7


【解决方案1】:

为 contentSize 添加一个 KVO 到 textView。如果获得更改,则重新加载该行。

  [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
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2020-09-23
    • 2023-03-17
    • 2013-10-03
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多