McDonal_11
McDonal_11

Reputation: 4075

Unable to set cell size according to label's text size in objective-c

I am trying for chat app. Chat working fine. Facing some UI issues.

1. I am using auto layout for label. So automatically label get expand according to the message size. But, I am having label in UITableViewCell. I couldn't calculate row height dynamically.

My Code:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGSize textSize = {268, CGFLOAT_MAX};
CGSize size = [message sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:14] constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = size.height  < 65 ? 65 : size.height;
return height;
}

My Label Sub class Code

- (void)drawTextInRect:(CGRect)rect
{
    self.textInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.textInsets)];
}

- (CGSize) intrinsicContentSize
{
    self.textInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    CGSize superSize = [super intrinsicContentSize] ;
    superSize.height += self.textInsets.top + self.textInsets.bottom ;
    superSize.width += self.textInsets.left + self.textInsets.right ;
    return superSize ;
}

The above code working for small messages, like 400 to 800 characters. More than that it is not working. Cell size not getting increase, as per label size. Kindly guide me.

My Output:

enter image description here

In the above screenshot, small messages displaying time and full message. If we type large text, 20% of message getting hide. kindly guide me. How to solve this?

Upvotes: 0

Views: 1341

Answers (1)

Arslan Asim
Arslan Asim

Reputation: 1302

Use Storyboard for your label and use only single label Set your label to have all 4 constraints, left,right,top,bottom Set number of lines 0. In your ViewController use these 2 methods,Table view will automatically set height depend on your text

 -(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   return UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
 return UITableViewAutomaticDimension;
}

Upvotes: 5

Related Questions