I’m looking how to align text to the top of screen, do you know how to?
import SwiftUI
struct RegisterSignInScreen: View {
var body: some View {
VStack {
Text("Welcome Back!")
.font(.title)
.fontWeight(.bold)
.multilineTextAlignment(.center)
.padding(.bottom, 5.0)
Text("Please sign in to your account")
.font(.subheadline)
.fontWeight(.bold)
.foregroundColor(Color.gray)
.multilineTextAlignment(.center)
}
}
}
struct RegisterSignInScreen_Previews: PreviewProvider {
static var previews: some View {
RegisterSignInScreen()
}
}
I tried to embed my VStack
in a ZStack
:
ZStack(alignment: .top)
But it didn’t work.
3
Answers
You can do this in a couple of ways, but the most obvious way is to simply add a
Spacer()
in the bottom of theVStack
Like so:
This will push your content in the
VStack
to the top.Alternatively, you can add a frame modifier and force your
VStack
height and add the alignment there using.frame
To see why this is happening you can add a background to your VStack or ZStack
What you will notice (maybe unexpectedly) is that the stack is only as big as it needs to be to contain the text items.
When you add alignment to the stack it aligns the content within the stack to the specified edge of the relatively small stack. It doesn’t align the stack to an edge of the screen, or change the size of the stack. What you’re actually looking to do is align the stack, not it’s content.
In order to align to the top of the screen you can make the stack fill the entire height of the screen. Either by adding a
Spacer()
at the bottom of the VStack that will fill the remaining vertical space pushing the content upwards, or by applying aframe
with.infinity
maxHeight:
and top aligned content to the VStack.Alternatively if required for your view, you can do a similar thing with a second stack containing your text stack like so:
ZStack(alignment: .top)
works, but not the same way as you think)try to do:
and you will understand why so 🙂
you need to use spacer 🙂