SwiftUI将VStack / HStack对齐到一个表中

时间:2020-07-18 19:32:01

标签: ios swiftui

enter image description here enter image description here我正在尝试对齐所有分隔线以创建一致的表视图,但是我无法使所有分隔线对齐。理想情况下,即使标题行也要使分隔符与列表对齐-但是对齐分隔符至关重要,以便标题行可以用作数据的键。

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 个答案:

答案 0 :(得分:1)

为常量.frame(width:)赋予常数Text

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)
}