Search code examples
swiftxcodechatcellmessenger

How to create bubble chat TableViewCell like in Messenger using XCode's Interface Builder?


I'm currently trying to implement a chat for my application but since I'm new at Swift development I got stuck at the part where I have to create the TableView cells for it. I was able to find 2 png images of "chat bubbles" (one for receiving and one for sending). I placed them in Assets and loaded them in an ImageView. Now my problem is how can I place a Label inside the ImageView and rescale it depending on how many lines of text are in the Label. The bubble should not exceed 66% of the screen's width.


Solution

  • OK, there are a few considerations:

    1. If you haven’t already, make your asset stretchable (where the corners aren’t stretched, but only the center is) by:

      • selecting the asset and zoom in so you can better refine the slices;
      • in the Xcode menu, choose “Editor” » “Show Slicing”;
      • click on “Start Slicing”: enter image description here
      • click on the center “horizontal and vertical stretching” button: enter image description here
      • move your guides to where you want them: enter image description here
      • now when you add the image view using this new stretchable asset and choose “Content Mode” of “Scale to Fit”, it will scale in such a way that the center is stretched but the edges aren’t: enter image description here

      Also see Xcode documentation “Add a resizable area to an image”.

    2. In your cell, now just add this image view and the label:

      • defining the label’s leading/trailing/top/bottom constraints to be inset from the edges of the image view;
      • define the label’s line count to zero;
      • define the image view’s width to be “>=” the container view width (with a multiplier of 66%);
      • obviously define your bubble’s appropriate leading/trailing/top/bottom constraints to its superview, too; and
      • make sure your cell is using automatic cell height.

    For the sake of completeness, the other approach is to make an @IBDesignable view where you draw the bubble yourself with a CAShapeLayer whose path is the cgPath of a UIBezierPath. This is what I’ve done in my chat apps. But this stretchable image approach works fine, too.

    By the way, if your speaker and listener bubbles are different colors, note that you might want to have flipped renditions of these bubbles for RTL languages.