Given this code :
import SwiftUI
struct ContentView : View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.lineLimit(nil)
.font(.body)
Spacer()
}
.background(Color.red)
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
It results in this interace:
How can I make the VStack
fill the width of the screen even if the labels/text components don't need the full width?
A trick I've found is to insert an empty HStack
in the structure like so:
VStack(alignment: .leading) {
HStack {
Spacer()
}
Text("Title")
.font(.title)
Text("Content")
.lineLimit(nil)
.font(.body)
Spacer()
}
Which yields the desired design:
Is there a better way?
I know this will not work for everyone, but I thought it interesting that just adding a Divider solves for this.
This is a useful bit of code:
Compare the results with and without the
.expandable()
modifier:-
Try using the .frame modifier with the following options:
This is described as being a flexible frame (see the documentation), which will stretch to fill the whole screen, and when it has extra space it will center its contents inside of it.
An alternative stacking arrangement which works and is perhaps a bit more intuitive is the following:
The content can also easily be re-positioned by removing the
Spacer()
's if necessary.This is what worked for me (
ScrollView
(optional) so more content can be added if needed, plus centered content):One more alternative is to place one of the subviews inside of an
HStack
and place aSpacer()
after it:resulting in :