SwiftUI:如何将VStack/HStack对齐成表格

3

在此输入图像描述在此输入图像描述我正在尝试对齐所有的分隔符以创建一个一致的表格视图,但我很难让所有的分隔符都对齐。理想情况下,即使标题行也应该有分隔符与列表对齐 - 但它们必须对齐,以便标题行可以作为数据的关键。

import SwiftUI

struct TableView: View {
    var teamNames = ["Sporting Kansas City", "Real Salt Lake", "Colorado Rapids", "Minnesota United"]
    
    var teamMP = ["2", "2", "2", "2"]
    
    var teamWins = ["2", "1", "0", "1"]
    var teamDraws = ["0", "1", "1", "1"]
    var teamLosses = ["0", "0", "1", "0"]
    
    var body: some View {
        return VStack() {
            HStack(spacing: 10) {
                Text("Club")
                    .padding(.leading)
                    .frame(width: 210.0, alignment: .leading)
                Spacer()
                Text("MP")
                Divider()
                    .frame(height: 20.0)
                Text("W")
                Divider()
                    .frame(height: 20.0)
                Text("D")
                Divider()
                    .frame(height: 20.0)
                Text("L")
                    .padding(.trailing)
            }
                .font(.subheadline)
                .foregroundColor(.gray)
            
            List(teamNames.indices) { i in
                Text("\(i+1)")
                Image("second")
                HStack(spacing: 10) {
                    Text("\(self.teamNames[i])")
                        .frame(width: 170.0, alignment: .leading)
                    Spacer()
                        .frame(width: 25.0)
                    Text("\(self.teamMP[i])")
                        .frame(width: 12) // replace 12 with any value for the exact result you're expecting
                    Divider()
                    Text("\(self.teamWins[i])")
                        .frame(width: 12) // doesn't have to match the above Text's width either could be any value and would still work
                    Divider()
                    Text("\(self.teamDraws[i])")
                        .frame(width: 12)
                    Divider()
                    Text("\(self.teamLosses[i])")
                        .frame(width: 12)
                }
            }
        }
    }
}

struct TableView_Previews: PreviewProvider {
    static var previews: some View {
        TableView()
    }
}
1个回答

5
为尾随的

我最初也尝试了这个方法,但第一行和其他行之间似乎仍然存在差异。我已经更新了问题,并使用您的建议更新了代码。@frankenstein - Garrett Graham
你需要在页眉中设置同样的.frame(width :),并调整前导Text或在前面或后面添加Spacer来获得所需的结果。 - Frankenstein

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接