Home > Net >  How to center VStack horizontally inside List with SwiftUI?
How to center VStack horizontally inside List with SwiftUI?

Time:01-24

I have a simple view:

var body: some View {
    NavigationView {
        List(months) { month in
            NavigationLink {
                MonthView(month: month)
            } label: {
                VStack(alignment: .center, spacing: 8, content: {
                    Text("abc")
                    Text("abcdef")
                    Text("a")
                })
            }
            .listRowBackground(
                Color(uiColor: mode.darkUnderlayBackgroundColor)
                    .clipped()
                    .cornerRadius(10)
            )
        }
        .navigationTitle(months.first?.descriptiveYear ?? "")
    }
}

and result is:

enter image description here

How can I center it in a whole view?

CodePudding user response:

You just need to set the maxWidth to infinity using the .frame modifier. This will allow it to expand horizontally to take up as much room as it needs

VStack(alignment: .center, spacing: 8) {
    Text("abc")
    Text("abcdef")
    Text("a")
}
.frame(maxWidth: .infinity)
  • Related