I have built three different cells in my storyboard and hooked all the outlets up, each cell has a unique identifier.
For example I have one cell which holds a picture, another which has a label and another with other contents, so they are all unique and each cell type requires its own height (dynamic or status, it doesn't matter).
However, how is it that I can make a cell with 'indentifier1' return a certain height and then the others cells returns different heights?
I know I can use - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
but I am unsure how to differentiate the cells.
I am using core data and fetch results for the tableview from that.
I have tried this with tags but its crashes at the first if
statement:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat cellHeight;
if ([[tableView cellForRowAtIndexPath:indexPath] tag] == 1) cellHeight = 170;
else if ([[tableView cellForRowAtIndexPath:indexPath] tag] == 2) cellHeight = 100;
else if ([[tableView cellForRowAtIndexPath:indexPath] tag] == 3) cellHeight = 140;
return cellHeight;
}
To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we'll need to make use of automatic dimension property. We'll see this with the help of an sample project.
On the Home tab, in the Cells group, click Format. Under Cell Size, click AutoFit Row Height. Tip: To quickly autofit all rows on the worksheet, click the Select All button, and then double-click the boundary below one of the row headings.
Updated
Use dynamic height of UITableView now as it's easy as UITableView automatically calculates it
Old
Use this method to your requirement below is an example:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//calculate height according to text and on basis of indexPath
if(indexpath.row == 0)
{
return 60.0f;
}
else if(indexpath.row == 1)
{
return 70.0f;
}
else
{
return 55.0f;
}
}
Note : if your size is not fixed then you will have calculate it then provide in above method according to your requirement.
You shouldn't call cellForRowAtIndexPath
within heightForRowAtIndexPath
or you'll enter an infinite loop which will cause the app crash.
You should determine the height of every cell in the same way you determine the type of the same cell in cellForRowAtIndexPath
.
That's the only solution I think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With