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!
- Our bubble will be based on an image which is easy stretchable
- For stretching our image we will use
resizableImage(withCapInsets capInsets: UIEdgeInsets, resizingMode: UIImageResizingMode) -> UIImagemethod of an
- Also we’ll calculate the hight of our bubble using
boundingRect(with size: CGSize, options: NSStringDrawingOptions = , attributes: [NSAttributedStringKey : Any]? = nil, context: NSStringDrawingContext?) -> CGRectmethod of an instance of
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
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.
Creating the Image Bubble
Add a new method and its call in
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.