NEW: Join my free 100 Days of SwiftUI challenge today! >>

How to create and compose custom views

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

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)
    }
}

SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.

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.0/5