Updated for Xcode 14.2
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")
.foregroundColor(.secondary)
var body: some View {
VStack {
title
subtitle
}
}
}
Download this as an Xcode project
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")
.foregroundColor(.secondary)
var body: some View {
VStack {
title
.foregroundColor(.red)
subtitle
}
}
}
Download this as an Xcode project
That doesn’t change the underlying style of title
, only that one specific usage of it.
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.