Creating Old Style Message Bubble With Swift

In present times chat applications have achieved the most popular category of apps, being installed by most smartphone users. Consequently, it has also marked the end of the SMS era. People have developed the habit of typing on highly popular Chat Applications like WhatsApp, WeChat, Line, Viber, Messenger, iMessage and send a quick message. Most of these apps also let you send pictures, video and voice clips along with regular text messages.

With the release of Apples iOS-7, the Message bubbles on the iMessage chat application got a complete makeover. The following two screenshots show the difference between the user interfaces of iMessage on iOS 6 and iOS 7 (or later).



Anyway, we are not going to start the discussion for determining the best out of the two. Our article is going to look into creating iOS 6 style message bubbles with Swift. In this blog, we will be implementing a custom chat bubble which will look something like below.


The Problem:

Creating the UILabel with numberOfLines = 0 is the best way to draw multiline labels as shown on the glossy bubbles. But the main problem is to draw the bubble. What happens if the message is as small as “Ok” or as long as an essay? Maintaining the bubble style with variable length of message text is the major cause of concern.

The Solution:

What we need is to create resizable image from a single template image.



For creating stretchable image, iOS 2 introduced an API on UIImage called

But this API was deprecated in iOS 5 but it is still available for development. To know more about this API head over to StackOverflow. iOS 5 introduced a new API for handling such scenario

Now, we will concentrate on making stretchable images as background image of our chat bubble, using this latest API on UIImage.

How does it work?

Let’s have a close look on the following drawing

Resizable Image

While creating a large UIImage from a smaller one, the original image is divided into 9 different portions as shown in the above picture. The division is based on the provided EdgeInsets while using the resizableImageWithCapInsets(_ capInsets: UIEdgeInsets) -> UIImage  API. Then the API does the following tasks to draw the larger image:

  1. Division areas 1, 3, 7, 9 are kept intact with the 4 corners of the target image to maintain the shape of the image.
  2. Division 2 and 8 are horizontally stretched to fill in the gap between the two top and bottom corners, respectively.
  3. Similarly division 4 and 6 are vertically stretched to fill in the gap between the two left and right corners, respectively.
  4. Division 5, in the middle, is both horizontally and vertically stretched to fill up the centre portion of the large image.

While creating the original image asset which is used to produce stretchable images we need to keep in mind the following things:

  1. The image should have high dpi.
  2. To minimize the size of the asset image we can keep the middle area as small as possible i.e. 1×1 Pixel.

Let’s Start Coding:

First download the configured project from GitHub. It comes with all image assets along with with a Util.swift class for handling the device detection and screen size calculations. Next, Open the Xcode project.

The Data Model:

Now we are going to create the data model to be shown in a single chat bubble, on screen. So what are the properties that we are going to consider? Our chat bubble can have a picture, some text and time of sending or receiving.

So it may contain

  1. An Image
  2. A Message Text
  3. Date

Anything else we are missing? What about introducing a type for a message bubble? It will be of type Mine if message is outgoing and Opponent if it is an incoming one. So the final contents are as follows

  1. An Image (Optional)
  2. A Message Text (Optional)
  3. Date
  4. Type (Incoming or outgoing)

Now create a new folder named DataModel in ChatBubbleScratch folder and add in ChatBubbleScratch group in file navigator. Create a new swift file named ChatBubbleData.swift in the specified group. Paste the following code at the very end of the file.


The Bubble:

In a similar fashion create a new folder named Custom View inside the ChatBubbleScratch folder and add it in file navigator as a group. In this group create a new CocoaTouch Swift class named ChatBubble.swift  keeping it Subclass of UIView. Now paste the following code in the class definition

So what we are doing here?

We are taking the chat bubble data and taking the origin.startY of the bubble frame in initialization method init(data:startY). Let’s try to understand it one by one

// 1. Class method framePrimary(_:startY) primarily calculates the frame for the bubble, depending upon the screen size of the device.

// 2. After basic resizing (If image size is larger than the view frame size), it draws the image on chat bubble.

// 3. This portion of code draws the message text if any.

// 4 & 5. As chat text label height is not known till we call sizeToFit() on label, we need to calculate proper values of width and height for that bubble with frame size of chatImage and labelChatText. Width and height of the chatBubble frame are then assigned to the proper value.

Let’s see what we have done so far:

Now paste the following code in viewDidLoad() function of ViewController.swift

Run your project using ⌘ + R. What do you see? It should look similar to the following

Screen Shot 2015-09-02 at 5.35.33 pm

If you are facing any problem, make sure that you have followed each step properly upto this point. If problem persists take a fresh start by downloading the scratch project from GitHub.

Wait, where is our bubble?

“These don’t look like bubbles. Why are they in simple view??”. Don’t worry, just keep reading.

Adding the resizable bubble image :

Paste the following line of code at the very end of init(data:startY) function of ChatBubble.swift  for creating bubble like structure.

Now, let’s select the file name of bubble image from type bubble data. An image view is created, taking the full width and height of the frame.

Have a closer look at the following lines

These edge insets should be given very precisely. You need to visually inspect and manually calculate these values while adding the image to image view.
Remember the following function signature. Yours would be something similar too.

Run your project again using ⌘ + R. Your screen should look like the following

Screen Shot 2015-09-02 at 6.16.16 pm

Great! The Bubble has finally appeared, but it does not look great as the imageViewChat

and labelChatText are not properly positioned with the bubble. Let’s try to position it properly.

Append the following code to position bubble image

Let’s see whether our effort has yielded any result or not

Run the project (⌘ + R) to see the result.

Screen Shot 2015-09-02 at 7.06.21 pm

Great, image and the chat text label have been properly aligned with the bubble image. But what about the left and right alignment of the bubble with the left and right edge of the screen? Are they properly maintained? Not yet!
Let’s try to keep a minimum distance from the edge of the screen. Paste the following code snippet below the one we added earlier.

Run the project. What you are seeing? You should get something like the one below.

Screen Shot 2015-09-02 at 7.15.51 pm

Got it right? ???? That nice! One more step, we are setting the background color of chat bubble as UIColor.clearColor()  instead of present value UIColor.lightGrayColor()

Let’s check the final result.

Screen Shot 2015-09-02 at 7.26.16 pm

That’s it folks!

Have a query on this tutorial? Please feel free to leave a comment below. If you are facing any problem while implementing the steps please download the fully configured project from GitHub.

Sauvik Dolui

Sauvik Dolui is an iOS enthusiast and ingenious blogger who loves all things design and technology. He works closely with clients across Fortune 500 companies to develop an effective technical strategy. Besides iOS apps he also loves to develop cross-platform mobile games. The Little Indian Archer, a bow-arrow game developed by Sauvik, can be found on App Store and Play Store as well. When he is not coding, he can be found travelling around the villages or reading a book. By the way he is crazy about soccer.

  • Rubens Talatinian

    Very Very Very good your explanation

    • Sauvik Dolui

      Thanks for your appreciation @rubenstalatinian:disqus .

  • Robin Stewie

    how would one be able to add an avatar to each message or the dates

  • addictingapps

    Can I easily put these in a CollectionViewController?

  • Yorky Menendez

    Excelente, funciona perfecto y muy fácil de personalizar!!!

  • Nitin Bhatia

    Unresolved identifier screensize…

    • Aviv Maman

      declare this :
      let screenSize: CGRect = UIScreen.mainScreen().bounds

      and then replace this = ScreenSize.SCREEN_WIDTH
      whit this one = screenSize.width

      have Fun 🙂

  • Surya Vijay

    Use of Unresolved identifier ‘ScreenSize’ how to handle this error

    • Aviv Maman

      declare this :

      let screenSize: CGRect = UIScreen.mainScreen().bounds

      and then replace this = ScreenSize.SCREEN_WIDTH

      whit this one = screenSize.width

      have Fun :))

  • Per Brondum Jakobsen

    Great overview and example. You should fix the ‘Horizontally expand areas to be 4,6 not 2.8 (under How does it work)

  • bikram

    i didn’t get the Github link of that project can you please send met that, so that i can get that bubble images and understand very clearly

  • bikram

    very good explanation, can i get the GitHub link so that i can view it more clearly

  • Saverio

    Can I have gitHub link?

  • Manab Kumar Mal

    Can you please make the codes designed for swift 3.0, it is really not working for Xcode 8.

  • kunal kushwaha

    i cant get it right.. not working for me after getting the image in view(unable to get the Bubble)