How to store views as properties
About 2 min
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
}
}
}
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
}
}
}
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