Reputation: 9732
Using the storyboard, I've created a custom cell for my table view, I've also created a custom class for it with all my properties.
Now, what would be the best way in making the cells height dynamic, where is the best way to do this? Should I do this in the custom class for the cell? Or in my table view controller?
I imagine it would make more sense to do this in the custom class, but then how should I do this? Once a specific label is filled in, it should change the height of the cell
Upvotes: 4
Views: 6084
Reputation: 942
Add these line into your "viewDidLoad" method
self.tableView.estimatedRowHeight = your height here
self.tableView.rowHeight = UITableViewAutomaticDimension;
Don't set default hight into delegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
}
Upvotes: 0
Reputation: 76
Use the following code
-(CGFloat)heightForText:(NSString *)str width:(int)width font:(UIFont *)font lineBreakMode:(NSLineBreakMode) lineBreakMode
{
CGSize textSize;
textSize = [str boundingRectWithSize:CGSizeMake(width, FLT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil].size;
return textSize.height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == self.yourTable)
{
NSMutableDictionary *dict = [self.yourArray objectAtIndex:indexPath.row] ;
return [self heightForText:[dict valueForKey:@"reviewDescription"] width:300 font:[UIFont fontWithName:kAppRegularFont size:15.0] lineBreakMode:0]+75;
}
return 70;
}
Upvotes: 4
Reputation: 14687
You cannot change the height of the cell from your custom drawing class.
You can do this in the viewController that has the UITableView only. Either by specifying a hardcoded row height for all cells, or by using the
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
and specifying a height for the cells here. If you want to have different heights for the cells, you should check the indexpath.row property and return the desired height value.
In case you want to change the height of an already drawn in screen cell, you will have to reload that cell to reflect the change using this:
Upvotes: 5
Reputation: 85
Set your view controller to be the delegate for the table view and then implement the following UITableViewDelegate method in the view controller:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
Upvotes: 0