SwiftUI中如何将List内的VStack水平居中?
问题:SwiftUI中让List行内的VStack水平居中
我编写了如下简单视图:
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 ?? "") } }
运行效果如下:

如何让该VStack在整个视图中水平居中?
解决方案
List的NavigationLink标签默认是左对齐布局,要让VStack水平居中,只需让它占据整个List行的可用宽度即可,有两种简单实现方式:
方式一:给VStack添加frame修饰符
直接为VStack设置maxWidth: .infinity,使其撑满行宽,结合自身的.center对齐属性,内部文本就会自动居中:
label: { VStack(alignment: .center, spacing: 8) { Text("abc") Text("abcdef") Text("a") } .frame(maxWidth: .infinity) // 关键代码 }
方式二:用HStack包裹并添加Spacer
通过HStack在VStack两侧添加Spacer(),强制VStack处于行的中间位置:
label: { HStack { Spacer() VStack(alignment: .center, spacing: 8) { Text("abc") Text("abcdef") Text("a") } Spacer() } }
两种方式都能实现需求,第一种代码更简洁,推荐使用。
内容的提问来源于stack exchange,提问作者kunass2
相关产品推荐
相关产品推荐

