Reputation: 9054
I have successfully resized my UITableViewCell
to fit it's content, but my UILabel is not resizing properly. This is how I'm resizing the cell:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str = @"My really long text";
CGSize constrainedSize = CGSizeMake(250, 9999);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"HelveticaNeue-Light" size:16.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.width > 250) {
requiredHeight = CGRectMake(0,0, 250, requiredHeight.size.height);
}
if (requiredHeight.size.height + 10 >= 60)
return requiredHeight.size.height + 10;
else
return 60;
}
I create my UILabel in my prototype cell in Storyboard
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Post-Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UILabel *text = (UILabel *)[cell viewWithTag:2];
text.text = @"My Label's Text";
[text sizeToFit];
return cell;
}
Upvotes: 0
Views: 1385
Reputation: 6352
I use this for my dynamic labels. First I know my label is constrained over 60px from the left and 67 from the right. So I know my label will have the screen width minus that padding to fit its content before wrapping. This method will give me the height of the title
no matter how many lines. I set a lowest height to 44
so that even if the user has uber small text I still have a nice sized cell. The label in my cell is 11 px from the top and 11 from the bottom of the content view so I add 22 to the height for padding.
+ (CGFloat)cellHeightForTitle:(NSString*)title
{
UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
NSString *text = title ?: @"test";
CGFloat hotizontalPadding = 127;
CGFloat desiredWidth = [UIScreen mainScreen].bounds.size.width - hotizontalPadding;
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];
UILabel *label = [[UILabel alloc] init];
label.attributedText = attributedText;
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
CGSize size = [label sizeThatFits:CGSizeMake(desiredWidth, CGFLOAT_MAX)];
font = nil;
attributedText = nil;
return MAX(44, size.height + 22);//top + bottom padding
}
Then in my table I call
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [MyCell cellHeightForTitle:@"Some long title"];
}
Upvotes: 2