Dynamic UITableView Cell Height Based on Contents

前端 未结 12 689
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 07:29

I have a UITableView that is populated with custom cells (inherited from UITableViewCell), each cell contains a UIWebView that is auto

12条回答
  •  再見小時候
    2020-12-05 07:40

    I tried many solutions, but the one that worked was this, suggested by a friend:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        int height = [StringUtils findHeightForText:yourLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:17.0f]];
    
        height += [StringUtils findHeightForText:yourOtherLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:14.0f]];
    
        return height + CELL_SIZE_WITHOUT_LABELS; //important to know the size of your custom cell without the height of the variable labels
    }
    

    The StringUtils.h class:

    #import 
    
    @interface StringUtils : NSObject
    
    + (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font;
    
    @end
    

    StringUtils.m class:

    #import "StringUtils.h"
    
    @implementation StringUtils
    
    + (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
        CGFloat result = font.pointSize+4;
        if (text) {
            CGSize size;
    
            CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName:font}
                                              context:nil];
            size = CGSizeMake(frame.size.width, frame.size.height+1);
            result = MAX(size.height, result); //At least one row
        }
        return result;
    }
    
    @end
    

    It worked perfectly for me. I had a Custom Cell with 3 images with fixed sizes, 2 labels with fixed sizes and 2 variable labels.

提交回复
热议问题