3

The cells in my table view are not auto-sizing their height to contain the content. I am using the "Basic" style for the cell prototype. I created a new test project containing only my view controller and a storyboard and it has the same issue. What am I doing wrong?

RowHeightTestController:

@implementation RowHeightTestController

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Test" forIndexPath:indexPath];

    // Configure the cell...
    cell.textLabel.text = @"Testing";
    cell.textLabel.font = [UIFont systemFontOfSize:60 + indexPath.row];

    return cell;
}

@end

The storyboard:

Storyboard

What I am seeing:

enter image description here

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Mike J
  • 1,144
  • 8
  • 12

2 Answers2

2

Create outlet/reference for tableView and on viewDidLoad , add

tableView.estimatedRowHeight = 44.0;
tableView.rowHeight = UITableViewAutomaticDimension;

For this to work, u must update the data in tableView's delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

Not willDisplay or any other delegates.

Also you must set the auto-layout constraints properly in the storyboard/xib.

For your simple cell view as shown in screenshot, set following constraints for UILabel as follows:

  • leading space to superview.
  • trailing space to superview
  • top space to superview
  • Bottom space to superview
Prajeet Shrestha
  • 7,978
  • 3
  • 34
  • 63
1

Try to set the properties of table :

tableView.estimatedRowHeight = 44.0;
tableView.rowHeight = UITableViewAutomaticDimension;

If content change then use notification to reload the table

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(contentSizeCategoryChanged:)
    name:UIContentSizeCategoryDidChangeNotification
    object:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self
    name:UIContentSizeCategoryDidChangeNotification
    object:nil];
}
// This method is called when the Dynamic Type user setting changes (from the system Settings app)
- (void)contentSizeCategoryChanged:(NSNotification *)notification
{
    [self.tableView reloadData];
}

For more watch this great answer : https://stackoverflow.com/a/18746930/3202193

Community
  • 1
  • 1
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136