Creating a Chat Bubble Which Looks Like a Chat Bubble in iMessage — the easy way

This article is the first of two articles about creating (iMessage style) chat bubbles.

This article is based on the original tutorial of Rob Kerr.

In this article, we’ll look at an easy way to create a chat bubble with tail. In the second, we’ll look at an advanced way.

This tutorial was created using Swift 4.1 and Xcode 9.2. The source code is available on Github.

This tutorial will teach you how to create a chat bubble with tail which looks like chat bubbles in iMessage. But it’s not about creating a fully fledged chat app. I’m going to focus specifically on how to create dynamically sized bubbles in the easy way. Let’s get started!

Implementation Approach

  1. Our bubble will be based on an image which is easy stretchable
  2. For stretching our image we will use resizableImage(withCapInsets capInsets: UIEdgeInsets, resizingMode: UIImageResizingMode) -> UIImage method of an UIImage instance
  3. Also we’ll calculate the hight of our bubble using boundingRect(with size: CGSize, options: NSStringDrawingOptions = [], attributes: [NSAttributedStringKey : Any]? = nil, context: NSStringDrawingContext?) -> CGRect method of an instance of String

Preparing Images

I created two text bubbles (for incoming and outgoing messages) in Adobe Illustrator and saved them as PDF files. Then added them to the project.

You can create your own bubbles in your favorite image editor or use mine. The PDF format is good because it automatically scales. So, you don’t need to prepare three images of different sizes.

Creating the Speech Bubble

Add following method implementation in our ViewController. Also add viewWillAppear() and insert in it our showOutgoingMessage() call.

Build and run.

Not bad. But let’s try to change our bubble’s dimensions.

Nice. Let’s add the ability to change the background color.

And finale part. Add a text label and calculate its sizes. Let’s assume that the maximum width of our bubble should not be more that 66% of the screen width.

Well done!

Creating the Image Bubble

Add a new method and its call in viewWillAppear().

Ok, it looks familiar. Suppose that the width of our image bubble should equals to half the screen.

And the final part. Add an another instance of UIImageView. We use maskView for masking our message image.

Nice! In the second article we’ll create these bubbles using a little more advanced technique.

The Source Code

The source code from this tutorial is available on Github.

Like what you read? Give Dima a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.