Skip to main content

How to store views as properties

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to store views as properties 관련

SwiftUI by Example

Back to Home

How to store views as properties | SwiftUI by Example

How to store views as properties

Updated for Xcode 15

If you have several views nested inside another view, you might find it useful to create properties for some or all of them to make your layout code easier. You can then reference those properties inline inside your view code, helping to keep it clear.

For example, this creates two text views as properties, then places them inside a VStack:

struct ContentView: View {
    let title = Text("Paul Hudson")
                    .bold()
    let subtitle = Text("Author")
                    .foregroundStyle(.secondary)

    var body: some View {
        VStack {
            title
            subtitle
        }
    }
}

Download this as an Xcode projectopen in new window

The text “Paul Hudson” in bold above the text “Author” in gray
The text “Paul Hudson” in bold above the text “Author” in gray

As you can see, just writing the property names in the stack is enough to place them.

However, even better is that you can attach modifiers to those property names, like this:

struct ContentView: View {
    let title = Text("Paul Hudson")
                    .bold()
    let subtitle = Text("Author")
                    .foregroundStyle(.secondary)

    var body: some View {
        VStack {
            title
                .foregroundStyle(.red)
            subtitle
        }
    }
}

Download this as an Xcode projectopen in new window

The text “Paul Hudson” in bold red above the text “Author” in gray
The text “Paul Hudson” in bold red above the text “Author” in gray

That doesn’t change the underlying style of title, only that one specific usage of it.

Similar solutions…
Composing views to create a list row | SwiftUI by Example

Composing views to create a list row
How to use @EnvironmentObject to share data between views | SwiftUI by Example

How to use @EnvironmentObject to share data between views
How to make two views the same width or height | SwiftUI by Example

How to make two views the same width or height
How to make views scroll with a custom transition | SwiftUI by Example

How to make views scroll with a custom transition
How to create and compose custom views | SwiftUI by Example

How to create and compose custom views

이찬희 (MarkiiimarK)
Never Stop Learning.