I am working on a chat application which shows the message and image of user. I have a table view and a custom cell in it.The cell has a UIlabel and UIImage. I tried various methods to resize the cell height dynamically based on the content text of label .I have set the numberofLines=0 in the storyboard itself and set height of cell a constant so that multiple lines can fit in. But it does not show multiple lines and as for height I used auto dimension but it didn't work as well . I also used the following link And I am using a custom cell of type messageTableViewCell which has a property of label inside it.
Here is the snapshot :-
My code in viewcontroller.m
- (void)viewDidLoad
{
self.tableView.estimatedRowHeight = 100.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
messageTableViewCell *cell = [self.messageTableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil)
{
cell = [[messageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
cell.messageLabel.text = [_messages objectAtIndex:indexPath.row];
cell.messageLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.messageLabel.numberOfLines=0;
[cell.messageLabel sizeToFit];
return cell;
}
EDIT
Instead of label I inserted a textview in the cell and modified it to :
- (void)textViewDidChange:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *)indexPath
{
static messageTableViewCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.messageTableView dequeueReusableCellWithIdentifier:@"cell"];
});
sizingCell.textMessage.text=_messages[indexPath.row];
CGFloat fixedWidth = sizingCell.textMessage.frame.size.width;
CGSize newSize = [sizingCell.textMessage sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = sizingCell.textMessage.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
CGFloat height= newFrame.size.height;
NSLog(@"%f is height ",height);
return height+5.0f;
}
But it is also not working and it cut off the upper half of text.