Reputation: 11999
In my table view I have made a custom cell as below image
Custom Cell
My problem is about the description text. The description text can contain a lot of lines. The text length is not fixed.
How can I auto fix the height of the cell and the description text so text comes full in it..
I am using label for the description text. And I don't think it is the good option. What else should I use.?
Auto resize LAbel
Output
Upvotes: 1
Views: 210
Reputation: 7804
You have to do a few things for that
First: You have to change the height of the table cell with
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *text = [[arrComments objectAtIndex:indexPath.row] valueForKey:json_KEY_Comment];
//THIS IS YOUR DESCRIPTION TEXT
if(text)
{
CGFloat width = 249.0;//WIDTH OF THE DESCRIPTION TEXT
UIFont *font = [UIFont systemFontOfSize:13];//FONT OF THE DESCRIPTION TEXT
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
size.height = ceilf(size.height);
size.width = ceilf(size.width);
return size.height + 40;//HERE size.height IS THE HEIGHT OF THE DESCRIPTION TEXT AND 40 IS
//HEADER TEXT AND IMAGE HEIGHT AND THE PADDING YOU WANT
}
else
{
return [tableView rowHeight];
}
}
Second: Set the line no of the description text to 0 so it will automatically take the required no of lines
Third: Set the auto resizing of THE DESCRIPTION TEXT
so it will automatically increase its height when the cell height changes[Note:if the label is in another view in the Cell Content View the parent of the label should also have the autoresizing set to this] Thank You
Upvotes: 0
Reputation: 966
you can use the blow code to get the height of cell as per text height you have to pass one text and its font size and you will get result
-(CGFloat)getHeightOfText:(NSString *)text FontSize:(int)fontSize{
UIFont *font = [UIFont fontWithName:@"Helvetica" size:fontSize];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){300, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
size.height = ceilf(size.height);
size.width = ceilf(size.width);
NSLog(@"%f",size.height);
return size.height + 50;
}
After that in :
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return //call above method like [self getHeightOfText:text FontSize:fontSize];
}
Upvotes: 0
Reputation: 729
You can get size of text like described here, now change the frame of your description UILable
and also change the cell height accordingly. You may need to apply constraints within your custom cell.
Upvotes: 0