iOS size table row based on content in textView

只愿长相守 提交于 2019-12-12 00:48:09

问题


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
}


来源:https://stackoverflow.com/questions/18814755/ios-size-table-row-based-on-content-in-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!