Dynamic UITableView Cell Height Based on Contents

前端 未结 12 683
佛祖请我去吃肉
佛祖请我去吃肉 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:36

    Here is code that I used for dynamic cell height when fetching tweets from twitter and then storing them in CoreData for offline reading.

    Not only does this show how to get the cell and data content, but also how to dynamically size a UILabel to the content with padding

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        Tweet *tweet = [self.fetchedResultsController objectAtIndexPath:indexPath];
    
        NSString* text = tweet.Text;
    
        TweetTableViewCell *cell = (TweetTableViewCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    
        //Set the maximum size
        CGSize maximumLabelSize = cell.tweetLabel.frame.size;
        CGPoint originalLocation = cell.tweetLabel.frame.origin;
    
        //Calculate the new size based on the text
        CGSize expectedLabelSize = [text sizeWithFont:cell.tweetLabel.font constrainedToSize:maximumLabelSize lineBreakMode:cell.tweetLabel.lineBreakMode];
    
    
        //Dynamically figure out the padding for the cell
        CGFloat topPadding = cell.tweetLabel.frame.origin.y - cell.frame.origin.y;
    
    
        CGFloat bottomOfLabel = cell.tweetLabel.frame.origin.y + cell.tweetLabel.frame.size.height;
        CGFloat bottomPadding = cell.frame.size.height - bottomOfLabel;
    
    
        CGFloat padding = topPadding + bottomPadding;
    
    
        CGFloat topPaddingForImage = cell.profileImage.frame.origin.y - cell.frame.origin.y;
        CGFloat minimumHeight = cell.profileImage.frame.size.height + topPaddingForImage + bottomPadding;
    
        //adjust to the new size
        cell.tweetLabel.frame = CGRectMake(originalLocation.x, originalLocation.y, cell.tweetLabel.frame.size.width, expectedLabelSize.height);
    
    
        CGFloat cellHeight = expectedLabelSize.height + padding;
    
        if (cellHeight < minimumHeight) {
    
            cellHeight = minimumHeight;
        }
    
        return cellHeight;
    }
    

提交回复
热议问题