Muhammad Umar
Muhammad Umar

Reputation: 11782

Changing height of UITableViewCell Dynamically

I am trying to show comments of each User in my TableView. The comments can BE accommodated by an Image.

Usually We can set height of a UITableViewCell as heightForRowAtIndex. However I want each Cell to Expand according to the Chat And if Image included upto image height.

How can I increase the height of UITablViewCell as per its contents?

Upvotes: 0

Views: 241

Answers (2)

ManiaChamp
ManiaChamp

Reputation: 857

USE THIS CODE IF YOU DONT HAVE CUSTOM CELL CLASS.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

         float PADDING = 0.5f; // USE FOR DIFFERNCE BETWEEN YOUR ENDING TEXT AND SEPERATOR
         UIImage *image =[UIImage imageNamed:@"test.png"]; // Some Image you want to put dynamically.
         NSString *text = @"Sometext That you want tro fill Dynamically";

         CGSize textSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:14.0f] constrainedToSize:CGSizeMake(270 , 1000)];
         return ((textSize.height+image.size.height+ PADDING * 3) + 30);
}

IF YOU HAVE CUSTOM CLASS THEN YOU HAVE TO PASS THE HIEGHT TO CUSTOM CELL TO MANAGE YOU LABEL HIEGHT SAME AS YOU EXPAND YOUR CELL OVERTHERE. YOU CAN DO IT SEPARATELY IN CELL CLASS BUT TO SYNCHRONIZE IT WITH YOUR ACTUAL HIEGHT F CELL. YOU HAVE TO PASS HIEGHT IN CUSTOM CLASS WHEN YOU WILL SETTING ITS VALUES.

Upvotes: 0

cjwirth
cjwirth

Reputation: 2013

You're still going to have to do it in heightForRowAtIndex:, except that you'll have to dynamically determine the height.

I'm envisioning something like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentModel *comment = self.comments[indexPath.row];
    CGFloat height = [CommentTableViewCell heightForComment:comment];
    return height;
}

And then in your CommentTableViewCell, you have a class method that goes something like:

// Calculates the height a CommentTableViewCell should be when configured with the given comment
+ (CGFloat)heightForComment:(CommentModel *)comment {
    // This part of the code will be very specific to your own project
    CGFloat height = BASE_HEIGHT;
    height += comment.image.size.height;
    height += comment.message.size.height;
    return height;
}

I know that this code probably doesn't match your code base, but it should give you a general idea of one way your goal can be accomplished.

Upvotes: 1

Related Questions