Resize UITableViewCell to UILabel's height dynamically

后端 未结 2 1147
醉话见心
醉话见心 2020-12-14 03:08

I want to resize cell\'s height according to the label\'s height and label\'s height according to text. Or is there any way I can resize the cell\'s height according to the

相关标签:
2条回答
  • 2020-12-14 03:57

    --For iOS7--

    Basing this off of Josh Vera's answer … place this in heightForRowAtIndexPath.

    I have my table data stored in an NSArray *tableData.

    // set the desired width of the textbox that will be holding the adjusted text, (for clarity only, set as property or ivar)
    CGFloat widthOfMyTexbox = 250.0;
    
    -(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        //Get a reference to your string to base the cell size on.
        NSString *cellText = [self.tableData objectAtIndex:indexPath.row];
        //set the desired size of your textbox
        CGSize constraint = CGSizeMake(widthOfMyTextBox, MAXFLOAT);
        //set your text attribute dictionary
        NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14.0] forKey:NSFontAttributeName];
        //get the size of the text box
        CGRect textsize = [cellText boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        //calculate your size
        float textHeight = textsize.size.height +20;
        //I have mine set for a minimum size
        textHeight = (textHeight < 50.0) ? 50.0 : textHeight;
    
        return textHeight;
    }
    

    I haven't tested it for iOS<7, but I believe it should work for that as well.

    0 讨论(0)
  • 2020-12-14 04:10

    THIS METHOD IS DEPRECATED SINCE iOS 7.0.

    There is a UITableView delegate method called heightForRowAtIndexPath that is called before you create a cell or a table.

    You could use the NSIndexPath passed to it to get the text at a specific row and use the sizeWithFont method from UIStringDrawing.h to compute a CGSize for that row.

    For example:

    CGSize size = [text sizeWithFont:font
                       constrainedToSize:maximumLabelSize
                       lineBreakMode:UILineBreakModeWordWrap];
    

    And finally you would return size.height.

    0 讨论(0)
提交回复
热议问题