iOS size table row based on content in textView

2019-08-28 02:29发布

问题:

I am trying to size a row in my table to the height of a textView so that the user does not have to scroll the textView, but rather scrolls the table. What I have implemented so far seems to work most of the time although sometimes the row height is a little too small, forcing the user to scroll the textview a little, or the row height is too much create a lot of whitespace after the text ends. How can I frame it just right?

Code:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Set the textview frame
    CGRect frame = self.contentTextView.frame;
    frame.size.height = [self.summary boundingRectWithSize:CGSizeMake(280, 0) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:self.contentTextView.font} context:nil].size.height + 60;
    self.contentTextView.frame = frame;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return the height for the rows
    if (indexPath.section == 0) {
        return 60;
    }
    if (indexPath.section == 3) {

        // Size content row based on text
        return [self.summary boundingRectWithSize:CGSizeMake(280, 0) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:self.contentTextView.font} context:nil].size.height + 100;
    }
    return 44;
}

回答1:

try this

- (CGFloat)tableView:(UITableView *)tv heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString* str = ... // here is a string which will be in text view

    CGSize boundingSize = CGSizeMake(textView.frame.size.width - 20, CGFLOAT_MAX);

    CGSize textSize = [str sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:boundingSize lineBreakMode:NSLineBreakByWordWrapping];

    return textSize.height + 40; // add aditional space for margins
}