NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How to create and compose custom views

Paul Hudson    @twostraws   

Updated for Xcode 12.0

One of the core tenets of SwiftUI is composition, which means it’s designed for us to create many small views then combine them together to create something bigger. This allows us to re-use views on a massive scale, which means less work for us. Even better, combining small subviews has virtually no runtime overhead, so we can use them freely.

The key is to start small and work your way up. For example, many apps have to work with users that look something like this:

struct User {
    var name: String
    var jobTitle: String
    var emailAddress: String
    var profilePicture: String
}

If you want to have a consistent design for user profile pictures in your app, you might create a 100x100 image view with a circular shape:

struct ProfilePicture: View {
    var imageName: String

    var body: some View {
        Image(imageName)
            .resizable()
            .frame(width: 100, height: 100)
            .clipShape(Circle())
    }
}

Your designer might tell you that whenever an email address is visible you should show a little envelope icon next to it as a visual hint, so you could make an EmailAddress view:

struct EmailAddress: View {
    var address: String

    var body: some View {
        HStack {
            Image(systemName: "envelope")
            Text(address)
        }
    }
}

When it comes to showing a user’s details, you could create a view that has their name and job title formatted neatly, backed up by their email address using your EmailAddress view, like this:

struct UserDetails: View {
    var user: User

    var body: some View {
        VStack(alignment: .leading) {
            Text(user.name)
                .font(.largeTitle)
                .foregroundColor(.primary)
            Text(user.jobTitle)
                .foregroundColor(.secondary)
            EmailAddress(address: user.emailAddress)
        }
    }
}

And you could even create a larger view that puts a ProfilePicture next to a UserDetails to give a single visual representation of users, like this:

struct UserView: View {
    var user: User

    var body: some View {
        HStack {
            ProfilePicture(imageName: user.profilePicture)
            UserDetails(user: user)
        }
    }
}

With this structure we now have several ways of showing users:

  • Just their picture
  • Just their email address
  • Just their job details
  • Everything all at once

More importantly, it means that when it comes to using all this work, our main content views don’t have to worry about what users look like or how they should be treated – all that work is baked into our smaller views.

This means we can create a UserView with an example user and have it just work:

struct ContentView: View {
    let user = User(name: "Paul Hudson", jobTitle: "Editor, Hacking with Swift", emailAddress: "paul@hackingwithswift.com", profilePicture: "paul-hudson")

    var body: some View {
        UserView(user: user)
    }
}
Hacking with Swift is sponsored by Instabug

SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.

Start your free trial!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.1/5

Link copied to your pasteboard.