如何将VStack的中心对齐到点SwiftUI

我在VStacks中有5个HStack,它横跨屏幕的宽度。 VStack包含Text个视图,这些视图的宽度均不同,因为它们显示的文本不同。我想做的是对齐每个VStack center ,以使它们彼此之间以及屏幕边缘均匀地分开。我知道屏幕的宽度(我用过GeometryReader),并且我很确定要获得每个VStack的x值,我需要将屏幕的宽度除以6,并且将中心VStack中的HStack应该落在屏幕的宽度上除以6,然后乘以代表其在VStack中的位置的数字(因此,{{ {1}}将为1)。由于所有HStack的宽度都不同,因此我认为无法使用VStacks中的spacing参数来完成此操作。因此,我需要一种使每个HStack的中心均等对齐的方法,以使每个VStack与屏幕边缘之间有一个均匀的空间。

这是我的代码:

HStack() {
        VStack(spacing: 10){
            Text("123")
                .foregroundColor(Color.white)
            Text("Value 1")
                .foregroundColor(Color.gray)
        }
        

        VStack(spacing: 10){
            Text("6534675")
                .foregroundColor(Color.white)
            Text("Value 23")
                .foregroundColor(Color.gray)
        }
        
        VStack(spacing: 10){
            Text("6534")
                .foregroundColor(Color.white)
            Text("Value 203")
                .foregroundColor(Color.gray)
        }
        
        VStack(spacing: 10){
            Text("1055")
                .foregroundColor(Color.white)
            Text("Value 4589")
                .foregroundColor(Color.gray)
        }
        
        VStack(spacing: 10){
            Text("4")
                .foregroundColor(Color.white)
            Text("Value 5")
                .foregroundColor(Color.gray)
        }
        
    }.frame(width: geo.size.width)
iCMS 回答:如何将VStack的中心对齐到点SwiftUI

如果知道VStack的宽度,则可以使用.padding()

语法示例:

VStack(spacing: 10){
        Text("4")
            .foregroundColor(Color.white)
        Text("Value 5")
            .foregroundColor(Color.gray)
    }.padding(10)
,

可以使用.position()定位视图的中心。

详细文档: https://developer.apple.com/documentation/swiftui/vstack-view-modifiers

本文链接:https://www.f2er.com/1790232.html

大家都在问