I\'m parsing a JSON string into a custom table view cell. How can I resize the label\'s height to fit the content text and also resize the cell to fit it\'s content.
Th
Use this to a dynamic sized cell:
Start by defining the following:
#define FONT_SIZE 13.0f
#define CELL_CONTENT_WIDTH 290.0f
#define CELL_CONTENT_MARGIN 19.0f
Implement the following helper method;
-(CGSize)frameForText:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize:(CGSize)size {
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
NSDictionary * attributes = @{NSFontAttributeName:font,
NSParagraphStyleAttributeName:paragraphStyle
};
CGRect textRect = [text boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
// This contains both height and width, but we really care about height.
return textRect.size;
}
In your UITableViewDelegate Height method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
NSString *text = [movie objectForKey:@"message"];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [self frameForText:text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint];
CGFloat height = MAX(size.height, 14.0f);
return height + CELL_CONTENT_MARGIN;
}
Set the frame and text in your UITableViews cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = @"PostsObject";
PostsObject *cell = (PostsObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PostsObject" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]];
self.tableView.backgroundView = imageView;
}
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
NSString *text = [movie objectForKey:@"message"];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [self frameForText:text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint];
cell.txtLabel.text = text;
cell.txtLabel.frame = CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 14.0f));
cell.published.text = [movie objectForKey:@"published"];
return cell;
}