0

I just had to make a UITableViewCell with automatic height calculation using the method systemLayoutSizeFittingSize:UILayoutFittingCompressedSize. Until my view had UILabels and UIImageViews, everything worked great. When I needed to replace one of the labels with UIButton, the method did not calculate the size correctly.

Do we need to supply some extra info to UIElements other than UILabels to work properly?

In the end I had to add TapGestures to the UILabels to make it work.

Here is the cell view:

enter image description here

The time "09:00 AM" and location are the labels here, these could have been buttons, if the method gave the result properly.

The idea is simple, create a cell xib with smallest screen size possible (iPhone 3.5 inch). Create a xib instance separately in your class, supply info to that instance (Time, location, etc) and run the systemLayoutSizeFittingSize:UILayoutFittingCompressedSize method to calculate the size.

_scheduleCell = [[[UINib nibWithNibName:@"HomeScheduleViewCell" bundle:nil] instantiateWithOwner:nil options:nil] objectAtIndex:0];

 CGSize fullSize = [_scheduleCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
nr5
  • 4,228
  • 8
  • 42
  • 82

1 Answers1

1

If you are using autolayout then you should use UITableViewAutomaticDimension. It will automatically count your row's height as per content, bu it must require autolayoot and properly set constraints.

As Apple documentation states,

To define the cell’s height, you need an unbroken chain of constraints and views (with defined heights) to fill the area between the content view’s top edge and its bottom edge. If your views have intrinsic content heights, the system uses those values. If not, you must add the appropriate height constraints, either to the views or to the content view itself.

You can use it like,

tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableViewAutomaticDimension

By this you can use button instead of label or any object.

Main thing is manage auto layout. it should be unbroken chain of constraints that means first object must have top constraint where last must have bottom constraint in cell's content view.

Hope this will help :)

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
  • Thanks for the answer. But is it documented somewhere, that `systemLayoutSizeFittingSize:UILayoutFittingCompressedSize` does not include UIButton and only UILabels. Because, the amount of code/time is same for both approaches. Unbroken chain of constraints is same for both of them. – nr5 May 30 '16 at 11:05
  • no, there is nothing documented like `systemLayoutSizeFittingSize:UILayoutFittingCompressedSize` does not include UIButton!! You must made some mistakes when giving constraints i think – Ketan Parmar May 30 '16 at 11:07