0

I have a customized a UITableviewCell. There is a title label and a detail label inside.

Now I want to adjust the detail label attributes according to the content. If the string size is greater than the frame then set the number of line to 2.

I have tried to put the code in the cellForRowAtIndexPath or layoutSubViews in the cell class.

The piece of code is like

TransportationViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
UIFont* font = cell.detailLabel.font;
NSDictionary* attribute = @{NSFontAttributeName:font};
const CGSize textSize   = [cell.detailLabel.text sizeWithAttributes: attribute];

if (textSize.width > cell.detailTextLabel.frame.size.width && cell.detailLabel.numberOfLines == 1) {

    NSLog(@"%lf, %lf, %lu", cell.detailLabel.frame.size.width, textSize.width, (long)cell.detailLabel.numberOfLines);
    cell.detailTextLabel.font = [UIFont systemFontOfSize:8];
    cell.detailTextLabel.numberOfLines = 2;

    [cell setNeedsLayout];
}

It actually passed the if condition but the setting of label doesn't work.

Dimuth
  • 713
  • 2
  • 11
  • 34
Mix
  • 459
  • 1
  • 7
  • 20
  • 1
    probably you are confusing between detailLabel and detailTextLabel? the second thing is that you do not need to call here '[cell setNeedsLayout]' it should work without this. – Nikita Aug 08 '16 at 08:07

2 Answers2

1

write below code in view didload

self.theTableView.estimatedRowHeight = 100;
self.theTableView.rowHeight = UITableViewAutomaticDimension;

[self.theTableView setNeedsLayout];
[self.theTableView layoutIfNeeded];

In cellForRowAtIndexpath cell.detailTextLabel.numberOfLines = 0;

Pavankumar
  • 288
  • 1
  • 10
0

set numberOfLines = 0;

this will solve your problem.

Edit 1: code for calculating dynamic height.

 CGSize boundingBox = [label.text boundingRectWithSize:constraint
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName:label.font}
                                              context:context].size;

Thne on the basis of this height you can do the further calculations.

For more info, you can check this answer https://stackoverflow.com/a/27374760/5660422

Community
  • 1
  • 1
Surbhi Garg
  • 414
  • 5
  • 19