How can I do variable height table cells on the iPhone properly?

前端 未结 3 1902
时光取名叫无心
时光取名叫无心 2020-12-12 19:56

My app needs to have variable height table cells (as in each table cell differs in height, not that each cell needs to be able to resize itself).

I have a solution t

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 20:34

    Here's what I use. NSString has a method that will tell you the dimensions of a textbox based on the font information and the height/width constraints you give it.

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NSString *text = [self getTextForIndexPath:indexPath];
        UIFont *font = [UIFont systemFontOfSize:14];
        CGSize size = [self getSizeOfText:text withFont:font];
    
        return (size.height + 11); // I put some padding on it.
    }
    

    Then you write a method pull the text for this cell...

    - (NSString *)getTextForIndexPath:(NSIndexPath *)indexPath
    {
        NSString *sectionHeader = [self.tableSections objectAtIndex:[indexPath section]];
        NSString *sectionContent = [self.tableData objectForKey:sectionHeader];
    
        return sectionContent;
    }
    

    And this is to get the size of the text.

    - (CGSize)getSizeOfText:(NSString *)text withFont:(UIFont *)font
    {
        return [text sizeWithFont:font constrainedToSize:CGSizeMake(280, 500)];
    }
    

提交回复
热议问题