SwiftUI 垂直未对齐的文本 [英] SwiftUI vertically misaligned text
问题描述
我有一些垂直错位的文本,我不知道为什么......
I have some vertically misaligned text and I don't know why...
代码:
struct IBANInputView: View {
@State var securityDigits = ""
@State var bankCode = ""
@State var accountNumber = ""
var body: some View {
HStack {
Button(action: onCountryButtonTapped, label: {
Text("NL")
.foregroundColor(Color.purple)
})
TextField("00", text: $securityDigits)
.fixedSize()
TextField("BANK", text: $bankCode)
.fixedSize()
TextField("0000 0000 00", text: $accountNumber)
}
}
func onCountryButtonTapped() {
print("LOL")
}
}
预览:
帧检查器:
为什么文本垂直未对齐,我该如何解决?
How come the text is vertically misaligned and how can I fix it?
推荐答案
发生这种情况是因为默认情况下 HStack
的垂直对齐是 .center
.通过将 HStack
的垂直对齐设置为 .firstTextBaseline
然后稍微调整按钮的垂直对齐,我能够实现您想要的.
This is happening because by default your HStack
's vertical alignment is .center
. I was able to achieve what you wanted by setting the HStack
's vertical alignment to .firstTextBaseline
and then adjusting the button's vertical alignment slightly.
HStack(alignment: .firstTextBaseline) {
Button(action: { print("haha") }, label: {
Text("NL")
.foregroundColor(Color.purple)
})
.alignmentGuide(.firstTextBaseline, computeValue: { return $0[.bottom] + 1.5 })
TextField("00", text: $securityDigits)
.fixedSize()
TextField("BANK", text: $bankCode)
.fixedSize()
TextField("0000 0000 00", text: $accountNumber)
}
这里我说按钮的第一个文本基线是按钮的 .bottom
,然后稍微向上移动该基线.您可能需要对值进行试验,但我发现这对于您的用例来说在视觉上最正确.
Here I'm saying the first text baseline of the button is the button's .bottom
and then moving that baseline up ever so slightly. You may have to experiment with values but I found this to be the most visually correct for your use-case.
在我看来,Button
中存在一个错误,但由于它没有正确宣传按钮本身的第一个文本基线.通过创建一个 .firstTextBaseline
-aware Button
子类",您可以在其他地方重用,而不是在任何地方进行微调整,这可能会更清晰.
It seems to me there's a bug in Button
though by virtue of it not properly advertising the first text baseline in the button itself. This could potentially be cleaner by making a .firstTextBaseline
-aware Button
"subclass" that you can reuse elsewhere instead of making micro-adjustments everywhere.
这篇关于SwiftUI 垂直未对齐的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!