1

就我而言,我将如何调整 a的大小以适应它包含UITableViewCell的 a 的高度?UITextView

我目前正在尝试使用以下代码来实现这一点:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    // init the font that we use
    UIFont *font = [UIFont fontWithName:@"SourceSansPro-Regular" size:16];

    if (indexPath.section == 0) {

        // get the text size of the thread
        CGSize textSize = [_thread.text sizeWithFont:font constrainedToSize:CGSizeMake(280, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];

        return textSize.height + 20;

    }

    // default
    return 60;

}

我觉得如果我可以访问UITableViewCellin 这个方法,那么我可以使用 in 它的contentSize属性UITextView,然后返回它。但我认为在执行流程的这一点上是不可能的。

我不能只调整那个缓冲区,因为它不会随着 get size 函数返回的文本大小而缩放。文本越短,缓冲区越大越明显。

这是调整 的高度UITableViewCell,但并没有显示它的所有UITextView内部。我已经UITextViewsizeWithFont:constrainedToSize:lineBreakMode:方法中指定了 的宽度,即280. 我已经指定我希望基本上没有最大高度,以便它可以使用CGFLOAT_MAX常量尽可能多地自动换行。我将一个单位缓冲区附加20到方法调用的结果高度,因为在 my20的 , 上方有一个单位缓冲区,我还想在它下面有一个单位缓冲区。UITextViewStoryboard20

不过,所有这一切的最终结果仍然是文本被剪掉了。这是我正在谈论的图片:

剪切的单元格内容

有任何想法吗?

4

1 回答 1

1

我将继续回答我的问题。答案分为两个步骤。

首先,UITextView在方法内部调整逻辑​​期间的大小tableView:cellForRowAtIndexPath:。确保UITextView. 我UITextView使用以下方法重新调整我的大小,在文本视图的子类UITableViewCell中:self.text

- (void)resizeTextView {

    // get the current frame size
    CGRect frame = self.text.frame;

    // set it to the height of the text view
    frame.size.height = self.text.contentSize.height;

    // set the new size of the text view
    self.text.frame = frame;

}

UITableViewCell接下来,我指定方法内部的高度tableView:heightForRowAtIndexpath:。这是最神秘的地方,因为要获得该行的高度,您必须计算将在该行中显示的任何文本的高度,以及您需要计算高度的任何其他内容。在我的场景中,是一个UITextView. 如果无法访问UITableViewCell此方法中的实例,您将不得不使用类似sizeWithFont:constrainedToSize:lineBreakMode:. 但是,我注意到这并没有为我返回一致的高度。或者至少,似乎不是为我的文本腾出足够空间的高度UITextView。不过,这就是问题所在。文本视图具有额外的左右填充以及不同的行高或其他内容,而不是该sizeWithFont方法使用的。

所以,在捏造了sizeWithFont一段时间的方法结果之后,我最终得到了以下代码:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    // init the font that we use
    UIFont *font = [UIFont fontWithName:@"SourceSansPro-Regular" size:16];

    if (indexPath.section == 0) {

        // get the text size of the thread
        CGSize textSize = [_thread.text sizeWithFont:font constrainedToSize:CGSizeMake(280 - 16, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];

        // text height + padding
        return textSize.height + 40;

    } else if (indexPath.section == 1) {

        // get the comment for this row
        Comment *comment = [_comments objectAtIndex:indexPath.row];

        // get the heights of the text areas
        CGSize textSize = [comment.text sizeWithFont:font constrainedToSize:CGSizeMake(280 - 16, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];

        return textSize.height + 40;

    }

    return 60;

}

在尺寸约束参数中,我减去了 16 个单位,因为在UITextView左右两侧都有大约 8 个单位的填充。这将使我们的结果更接近我们对文本高度的预期。

我还在 40 个单位的最终高度上添加了一些填充,因为行本身需要在UITextView.

给你!希望有帮助。

于 2012-08-13T15:12:17.480 回答