Categories
SwiftUI

Build a Chat App Interface With SwiftUI

Every app has messaging now. Here’s how you can quickly build messaging into your app

Chat app, SwiftUI, UI, Texting app, text app

Chat Model

Let’s start by creating an enum for the bubble positions. Bubbles can be on the right or left side of the screen:

Now, we can create our model that stores our messages, bubbles’ positions, and the user input text. For this tutorial, we are going to store the last chat bubble’s position in a variable so we can alternate between the left and right bubble positions:


Chat Bubble

We need to create a chat bubble by utilizing ViewBuilder. Inside our body variable, we can create a bubble shape. In this tutorial, we are using RoundedRectangle and an arrow system image to make the bubble shape.

If the bubble is on the right, then the chat bubble shouldn’t expand to the left end of the screen and vice versa. Use padding to control how much the bubble can expand. Use the frame modifier to adjust the bubble’s alignment:


Custom ScrollView

If you want your ScrollView to scroll automatically, you can use the code below provided by Asperi on Stack Overflow:


Chat Construction

Now, we can use our model and custom ScrollView to loop through the messages and add them to the UI. Inside the ChatBubble content closure, we will have a text view that takes the last message saved in our array of messages.

Under our custom ScrollView, we need to add a text editor with a send button. We are using a text editor instead of a text field because we don’t want the return button on the keyboard to dismiss the keyboard. Instead, we want it to add a new line.

Inside our button closure, when the text editor is not empty, we need to add the message and its position to the model’s arrays and then empty the text editor:

Lastly, add the Chat view inside our ContentView and run the application:

Chat app made with SwiftUI, Texting app, Texting SwiftUI, TextEditor
Chat app made with SwiftUI.

All done! Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *