UITextView sizeThatFits返回的大小与boundingRectWithSize不同

需要UITextView所需的高度。 sizeThatFits返回更大,但正确的高度比boundingRectWithSize更高。 为什么存在差异?

在两个地方我需要知道高度。 在cellForRowAtIndexPathheightForRowAtIndexPath

我不认为在heightForRowAtIndexPath创建UITextView只是为了知道需要什么高度是有效的。

您知道在heightForRowAtIndexPath计算UITextView高度有哪些解决方法?

我上个月遇到了类似问题的UITableView,我使用boundingRectWithSize来计算大小,它实际上是正确的。 然后我把它放到UITextView中。

我犯的一些错误:

  1. 我忘记在计算和UITextView时设置相同的字体大小
  2. UITextView有边距,我将手动将其添加到heightForRowAtIndexPath并将textContainerInset设置为相同的边距。

希望它能帮到你。

 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSInteger section = indexPath.section; NSUInteger axisIndex = section - 2; yAxis *yAxisObj = self.yAxisInfoArray[axisIndex]; boundingRect = [yAxisObj.yAxisDescription boundingRectWithSize:CGSizeMake(self.descriptionViewWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.contentFont} context:nil]; return boundingRect.size.height + TEXT_TOP_MARGIN + TEXT_BOTTOM_MARGIN; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellId = @"ChartDescriptionCell"; ChartDescriptionCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId]; if (!cell) { cell = [[ChartDescriptionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId]; cell.textView.bounces = NO; cell.textView.showsHorizontalScrollIndicator = NO; cell.textView.showsVerticalScrollIndicator = NO; cell.textView.font = self.contentFont; cell.textView.textColor = [UIColor colorWithHex:@"#333333"]; cell.textView.textContainerInset = UIEdgeInsetsMake(TEXT_TOP_MARGIN, -5, TEXT_BOTTOM_MARGIN, -5); } NSInteger section = indexPath.section; NSUInteger axisIndex = section - 2; yAxis *yAxisObj = self.yAxisInfoArray[axisIndex]; cell.textView.text = yAxisObj.yAxisDescription; } return cell; } 

boundingRectWithSize返回文本的大小,因此您应手动提供字体。

sizeThatFits返回UITextView的大小,里面有这个文本

如果您指向iOS 8及更高版本,则可以使用动态单元格高度,这非常容易。 对于iOS 7,您需要一些解决方法。

教程: http : //www.raywenderlich.com/87975/dynamic-table-view-cell-height-ios-8-swift

相关问题的答案很好: 在UITableView中使用自动布局来获取动态单元格布局和可变行高