您可以使用对齐指南。这个答案也vs
以屏幕为中心,而不仅仅是相对于彼此。
代码:
struct ContentView: View {
private let games: [Game] = [
Game("Manchester United", vs: "Arsenal"),
Game("Liverpool", vs: "Newcastle United")
]
var body: some View {
ZStack(alignment: .centerVs) {
Color.clear
.frame(height: 0)
.frame(maxWidth: .infinity)
.alignmentGuide(.centerVs) { d in
d[HorizontalAlignment.center]
}
VStack(alignment: .centerVs) {
ForEach(games) { game in
HStack {
Text(game.team1)
Text("vs")
.alignmentGuide(.centerVs) { d in
d[HorizontalAlignment.center]
}
Text(game.team2)
}
}
}
}
}
}
struct Game: Identifiable {
let id = UUID()
let team1: String
let team2: String
init(_ team1: String, vs team2: String) {
self.team1 = team1
self.team2 = team2
}
}
extension HorizontalAlignment {
private struct CenterVsAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
context[HorizontalAlignment.center]
}
}
static let centerVs = HorizontalAlignment(CenterVsAlignment.self)
}
extension Alignment {
static let centerVs = Alignment(horizontal: .centerVs, vertical: .center)
}
结果: