Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI VStack Alignment Bug?

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()
    }

}
like image 441
Jack Avatar asked Jun 04 '26 12:06

Jack


2 Answers

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 :)

like image 142
Asperi Avatar answered Jun 07 '26 18:06

Asperi


I agree with the author, the behavior is strange...at least. Alignment for VStack subviews does not work in case:

VStack(alignment: .leading) {
    Text("Hello, world!")
    Text("Hello, world!")
}
.frame(width: 200, height: 200)

but works in case:

VStack {
    Text("Hello, world!")
    Text("Hello, world!")
}
.frame(width: 200, height: 200, alignment: .leading)

If this is not a bug then definitively a poor realisation of the "declarative" approach.

like image 20
Andrey Popov Avatar answered Jun 07 '26 20:06

Andrey Popov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!