Elevate User Experience: Create Default Avatars in SwiftUI

Mayank Choudhary
2 min readAug 1, 2023

--

We often encounter the need for displaying user avatars in our applications. However, handling default avatars for users without profile pictures can be tedious and repetitive. This blog post explores a simple and efficient solution to this challenge using SwiftUI and Swift extensions.

By the end of this tutorial, you’ll have a clean and personalized default avatar generator that adds a touch of uniqueness to your app’s user interface.

  1. Setting Up the User Model : We’ll begin by defining our User model, representing the user's full name. To keep things organized, we'll create a sample list of users as an extension of the User model. This way, we can quickly test our default avatar generator with real user data.
User.swift

2. Creating a Useful String Extension: To simplify the process of accessing individual characters in a string, we’ll add a new folder named “Extensions” to our project. Inside this folder, we’ll create a String extension that provides easy access to each character by using their index.

Extensions.swift

With this String extension, we can now effortlessly extract characters from any string, which will be instrumental in generating personalized avatars.

3. Custom Default Avatar View: Now comes the exciting part — let’s create a custom DefaultAvatar view that generates personalized avatars for each user. We'll utilize the String extension we created earlier to extract the first initials of the user's first name and last name.

DefaultAvatarView.swift

In this custom DefaultAvatar view, we create a unique representation of the user's initials within a circular shape. The personalized avatar provides a quick identification of the user while enhancing the visual appeal of your app.

4. Implementing the Avatar Generator: Finally, we’ll integrate the DefaultAvatar view into our ContentView. Using a List, we'll display a list of users with their personalized default avatars generated from their initials.

ContentView.swift

In the ContentView, we leverage the List view to display the list of users, each accompanied by their personalized default avatar. As you scroll through the user list, the avatars will dynamically adjust to reflect the initials of each user.

That’s it. Have fun creating personalized avatars for your app! 🚀🎨

Photo by Mika Baumeister on Unsplash

--

--

Mayank Choudhary
Mayank Choudhary

Written by Mayank Choudhary

Self-Taught Developer 👨‍💻 • Open Source Enthusiast• Postman API fest 22 mentor• Cloud Native Hackathon Winner • Hacktoberfest 2020 • Harvard University CS50x

No responses yet