HStack 元素居中

问题描述 投票:0回答:1

在我的 VStack 中我有这个:

VStack {
    Text("\(match.initiator!) VS \(match.performer!)")
        .border(Color.green, width: 1)
        .font(.system(size: 28, weight: .bold))
        .foregroundColor(Color.black )
                
        HStack {
            Text(match.outcome! ? "WIN : LOSE" : "LOSE : WIN")
            .font(.system(size: 20, weight: .bold))
        }
}

问题是“WIN”和“LOSE”之间的冒号正在移动,具体取决于结果。我希望它始终位于中心,无论胜利和失败的位置如何,也无论“胜利”和“失败”文本部分的长度如何。如何使整个措辞围绕“:”字符居中?

swiftui centering
1个回答
1
投票

如果文本元素单独显示,则可以在第一个和最后一个元素上设置

maxWidth: .infinity
,这将使它们共享可用空间。然后“:”将被精确地夹在中间。

HStack {
    Text(match.outcome! ? "WIN" : "LOSE")
        .frame(maxWidth: .infinity, alignment: .trailing)
    Text(":")
    Text(match.outcome! ? "LOSE" : "WIN")
        .frame(maxWidth: .infinity, alignment: .leading)
}
.font(.system(size: 20, weight: .bold))

或者,如果您希望

HStack
具有所需的最小宽度,您可以使用隐藏的占位符来建立各个单词的足迹。然后将单词本身显示为覆盖在足迹上:

private var winLoseFootprint: some View {
    ZStack {
        Text("WIN")
        Text("LOSE")
    }
    .hidden()
}
HStack {
    winLoseFootprint
        .overlay(alignment: .trailing) {
            Text(match.outcome! ? "WIN" : "LOSE")
        }
    Text(":")
    winLoseFootprint
        .overlay(alignment: .leading) {
            Text(match.outcome! ? "LOSE" : "WIN")
        }
}
.font(.system(size: 20, weight: .bold))
© www.soinside.com 2019 - 2024. All rights reserved.