Resize UITableViewCell to UILabel's height dynamically

后端 未结 2 1161
醉话见心
醉话见心 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.

提交回复
热议问题