Home > Net >  SwiftUI - Data being displayed in center even when alignment is specified as "leading"
SwiftUI - Data being displayed in center even when alignment is specified as "leading"

Time:07-08

I have 4 vertical stacks within a parent vertical stack. Only the data that's in first vertical stack should be center and rest all of them should be left alignment. I have set the alignment on those 4 vertical stack i.e. for 1st vertical stack alignment is center and for rest 3 of them it's leading. However when I see it on the simulator, first 3 vertical stack's data are in the center and only last is left aligned.

How do I fix this?

Code:

struct CustomView: View {
    var body: some View {
        VStack {
            VStack(alignment: .center) {
                Text("Testing testing").lineLimit(2).font(.headline)
                Spacer()
                Spacer()
            }
            VStack(alignment: .leading) {
                Text("July 7, 2022").lineLimit(2).font(.subheadline)
                Spacer()
                Spacer()
            }
            VStack(alignment: .leading) {
                Text("9am - 5pm").lineLimit(2).font(.subheadline)
                Spacer()
                Spacer()
            }
            VStack(alignment: .leading) {
                Text("Hello World").lineLimit(2).font(.subheadline)
                Text("This string is very very very long to wrap onto next line").lineLimit(2).font(.system(size: 10.0))
            }
            Spacer()
            Spacer()
        }
    }
}

Screenshot of the view:

enter image description here

CodePudding user response:

A stack (any of H/V/Z) alignment specify alignment for children, not for itself, so as each of provided VStack has only one sized child (i.e. Text) there is nothing inside to be aligned.

A solution is to put alignment to parent and make specific case for first child, like

var body: some View {
    VStack(alignment: .leading) {    // << here !!
        VStack {
            Text("Testing testing").lineLimit(2).font(.headline)
            Spacer()
            Spacer()
        }.frame(maxWidth: .infinity)   // << centered by-default
        VStack {
            Text("July 7, 2022").lineLimit(2).font(.subheadline)
            Spacer()
            Spacer()
        }
        VStack {
            Text("9am - 5pm").lineLimit(2).font(.subheadline)
            Spacer()
            Spacer()
        }
        VStack(alignment: .leading) {     // << keep, because of many inside
            Text("Hello World").lineLimit(2).font(.subheadline)
            Text("This string is very very very long to wrap onto next line").lineLimit(2).font(.system(size: 10.0))
        }
        Spacer()
        Spacer()
    }
}
  • Related