Search code examples
objective-ciosipadimessage

Expandable Chat bubble UITableViewCell iOS


I currently have an application that has a messaging feature. It allows users to chat with one another. Currently the messages appear from the bottom up (I was able to accomplish this by rotating the table and the cells). Right now to distinguish between the sender and the receiver I use different colored text.

I want to use a bubble image as a background for the messages instead so that the app looks a lot more like iMessage. I know there is away to resize an image but I cannot get my head around this. Will I need a special kind of image? If so, how can I resize that image so that it fits the text and then place it as the background?

Thanks in advance for your help.

-EDIT- Code I am using to generate the cell with the bubble:

[self.textLabel setFont:[UIFont fontWithName:@"Helvetica" size:20]];
[self.textLabel setNumberOfLines:0];
CGSize size = [message.message sizeWithFont:self.textLabel.font];

    [self.textLabel setFrame:CGRectMake(690.0f - (size.width + 5.0f), 8.0f, size.width + 5.0f, size.height)];
    UIImage *bubble = [[UIImage imageNamed:@"aqua.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
    UIImageView *bubbleView = [[UIImageView alloc] initWithFrame:CGRectMake(704 - (size.width + 25.0f), 2.0f, size.width + 25.0f, size.height + 15.0f)];
    bubbleView.image = bubble;
    self.backgroundColor = [UIColor clearColor];
    self.opaque = NO;
    self.backgroundView = bubbleView;

Solution

  • There are several ways to implement such a feature. Probably the easiest solution is using the
    -resizableImageWithCapInsets: method of UIImage. You could create a tableview cell for each chat message and on the background draw this image and make the image stretch at the cap inset points.

    In the tableView delegate method -tableView:heightForRowAtIndexPath: you can set the height of the cell, making use of the NSString method
    -sizeWithFont:constrainedToSize:lineBreakMode: to calculate the proper height of the cell's contents (the actual chat message).