How to create dynamic height tableview cell has been a very daunting task especially when you have to calculate and return variable row height in
[code]- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;[/code]
But with autolayouts its very simple.you just have to make sure that the constraints of the tableview cell subviews are added in such a way that they push on the boundries of UITableViewCell.
And in ViewDidLoad you just need to set
[code]
tblTestDynamic.estimatedRowHeight=18; // a close estimation
tblTestDynamic.rowHeight =UITableViewAutomaticDimension;
[/code]1.Creating Cell with Auto LayoutSample table view cell with a single lable with following constraints (i am using Xib and assume knowledge of basic UITableView)
Set label number of line =0 this allows for dynamic decision on number of lines.
set uilabels tag to one.
2.Setting up code :- set up a data source with varialble length text and Dynamic dymension code in view did load
[code]- (void)viewDidLoad {
[super viewDidLoad];
datasource=@[@”A TEXT”,@”A VERYY LOO LOOO LOOO NG TEXT WE HAVE A VERY NICE TUTORIAL A VERY NICE TEXT TUTORIAL GOOD FOR US A VERY LONG TEXT”,@”A VERYY LOO LOOO LOOO NG TEXT WE HAVE A VERY NICE TUTORIAL A VERY NICE TEXT TUTORIAL GOOD FOR US A VERY LONG TEXT A VERYY LOO LOOO LOOO NG TEXT WE HAVE A VERY NICE TUTORIAL A VERY NICE TEXT TUTORIAL GOOD FOR US A VERY LONG TEXT A VERYY LOO LOOO LOOO NG TEXT WE HAVE A VERY NICE TUTORIAL A VERY NICE TEXT TUTORIAL GOOD FOR US A VERY LONG TEXT”,@”A VERYY LOO LOOO LOOO NG TEXT WE HAVE A VERY NICE TUTORIAL A VERY NICE TEXT TUTORIAL GOOD FOR US A VERY LONG TEXT”,@”A VERYY LOO LOOO LOOO NG TEXT WE HAVE A VERY NICE TUTORIAL A VERY NICE TEXT TUTORIAL GOOD FOR US A VERY LONG TEXT”];
tblTestDynamic.estimatedRowHeight=18;// a very close estimation closer the better
tblTestDynamic.rowHeight =UITableViewAutomaticDimension; // magic 🙂
// Do any additional setup after loading the view, typically from a nib.
}
[/code]
3. Set up UITableView datasource
[code]#pragma mark – table view data source
-(NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return 5;
}
// configure the custom table view cell
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// dequeue a table view cell
UITableViewCell *cell
= [tableView dequeueReusableCellWithIdentifier:@”testReuse”
forIndexPath:indexPath];
// set its title label
UILabel *title = (UILabel *)[cell viewWithTag:1];
title.text = [datasource objectAtIndex:indexPath.row];
// to diffrentiate between rows
if(indexPath.row%2==0)
cell.backgroundColor=[UIColor redColor];
else
cell.backgroundColor=[UIColor yellowColor];
return cell;
}
[/code]
you are done now run the project in your simulator
UITableViewAutomaticDimension is available iOS5 and above.We have Dynamic height self adjusting UITableViewCells.