aherlambang
aherlambang

Reputation: 14418

resizable UITableViewCell

Is it possible to create a custom UITableViewCell that resizes depending on the length of the text that I want to put into? If possible, how do I do this?

Upvotes: 0

Views: 624

Answers (3)

Andrew Zimmer
Andrew Zimmer

Reputation: 3191

Absolutely,

I like to set all the data on my cell by passing it a model (just an NSObject with data in it). Then I create a custom cell that can have its data set by the model, and I add a class level function to return the size. It looks like this.

TableViewDelegate:

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    XTableViewCellModel *model = [self modelForIndexPath:indexPath];
    return [XTableViewCell cellHeight:model];
}

XTableViewCell:

+(CGFloat)cellHeight:(XTableViewCellModel*)model {
    CGSize titleSize = [model.title sizeWithFont:model.titleFont
                         constrainedToSize:CGSizeMake(280, 9999)
                             lineBreakMode:UILineBreakModeTailTruncation];
    return titleSize.height;
}

Note that setting lineBreakMode to UILineBreakModelTailTruncation only takes effect after the height of 9999 points is reached. Until then the text wraps normally.

Check out my open source framework around this stuff. It has a lot of resizable cell types built by default: https://github.com/andrewzimmer906/XCell

Upvotes: 1

Sudhanshu
Sudhanshu

Reputation: 3960

@EquinoX yes it is possible through heightForRowAtIndexPath delegate....Please have a look on this and Dynamic Height UITableViewCell they have same thing you are asking.

Good Luck!

Upvotes: 1

k-thorat
k-thorat

Reputation: 5123

Look at this Sample Code it uses exactly what you looking for.

Upvotes: 0

Related Questions