Invalid UITableViewCell height with UITableViewAutomaticDimension

I create a custom cell with two multi-line labels and bind these labels to all sides. When in -tableView:heightForRowAtIndexPath: for iOS> = 8, I return UITableViewAutomaticDimension . But when a table view appears, the cell height is greater than it should be. After scrolling down and then scrolling up, the cell takes up a normal height. How to fix this behavior?

Code for height:

  - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) { return UITableViewAutomaticDimension; } static CCTopicTableViewCell *cell; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ cell = [tableView dequeueReusableCellWithIdentifier:@"topicCellIdentifier"]; }); cell.topic = [self.topics topicAtIndexPath:indexPath]; cell.bounds = CGRectMake(0, 0, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(cell.bounds)); [cell setNeedsLayout]; [cell layoutIfNeeded]; CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; return size.height + 1; } 

And the result:

UCSK2.png

After scrolling:

fnh6X.png

+5
source share
4 answers

The problem disappeared when I did not specify a tableView with a RowHeight rating for iOS 8 and updated preferredMaxLayoutWidth every time I set the text for multi-line labels

+9
source

Set the automatic size in the viewDidLoad () or viewWillAppear () method (both codes in one place)

  tableView.rowHeight = UITableViewAutomaticDimension; tableView.estimatedRowHeight = 160.0;//(Maximum Height that should be assigned to your cell) 

Visit Using auto-layout in UITableView for dynamic layouts of cells and row heights in a table , an intuitive guide for iOS 7 and iOS 8

+2
source

I solved this problem by setting the text property for multi-line labels to "nil":

 override func prepareForReuse() { _label.text = nil } 

The correct settings for the "RowHeight" and "rowHeight" table must also be set:

 _tableView.estimatedRowHeight = 44 _tableView.rowHeight = UITableViewAutomaticDimension 
+2
source

Automatic dimension does not work well for some UILabel if this label is aligned with a different label using upper edges or lower edges . Just make sure you don't have such alignments.

+1
source

Source: https://habr.com/ru/post/1212862/


All Articles