3

I've been building an application in SwiftUI recently and today I'm noticing that the VStack Alignment is having some strange behavior. No matter the alignment I use, the view isn't aligning outside of the center. See below:

VStack(alignment: .trailing, spacing: 0) {
    Text("Hello, World!")
}

enter image description here

VStack(alignment: .center, spacing: 0) {
    Text("Hello, World!")
}

sw

It's doing this in both the preview and the simulator, I'm trying to align my text to the right edge of the screen.

Full Code:

import SwiftUI

struct DemoView: View {
    var body: some View {
        VStack(alignment: .center, spacing: 0) {
            Text("Hello, World!")
        }
    }
}

struct DemoView_Previews: PreviewProvider {
    static var previews: some View {
        DemoView()
    }

}
pawello2222
  • 23,992
  • 12
  • 59
  • 94
Jack
  • 244
  • 5
  • 17

2 Answers2

6

The VStack(alignment:...) is for aligning subviews, but you have only one subview, so nothing to align

By default all stacks are tight to content (just add .border to your test VStack/s and you see the result, so there is no area to move content.

What you expected is solved by giving frame alignment in stack providing screen-wide area:

demo

VStack {
    Text("Hello, World!")
}.frame(maxWidth: .infinity, alignment: .trailing)

P.S. SwiftUI still has many bugs, but not here :)

Asperi
  • 123,447
  • 8
  • 131
  • 245
0

This can be solved with a Spacer.

Alignment leading:

var body: some View {
        HStack {
            Text("Hello, World!")
            
            Spacer()
        }
    }

Alignment trailing:

var body: some View {
        HStack {
            Spacer()
            
            Text("Hello, World!")
        }
    }
dankito
  • 638
  • 3
  • 11