如何使文本与 SwiftUI 中的填充正确对齐?

How to make text properly aligned with padding in SwiftUI?

所以我有这两个文本,我试图将它们基本上对齐到同一像素,但似乎一个比另一个偏移更多。像这样,底部的一个似乎比另一个更靠左。

代码如下:

VStack(alignment: .leading) {
                    Text("Enter your phone number")
                        .padding(15)
                        .frame(alignment: .leading)
                        .foregroundColor(Color.white)
                        .font(Font.custom("URWDIN-Thin", size: 30))
                //Subtitle
                    Text("You will be sent a code for verification")
                        .padding(15)
                        .frame(alignment: .leading)
                        .foregroundColor(Color.white)
                        .font(Font.custom("URWDIN-Thin", size: 16))

知道为什么会这样吗?

您选择了一种字体,其中大写字母“E”具有明显的左侧轴承。 Left side bearing 是从“笔位置”到字形紧边界框左边缘的距离。

这就是您的文本行看起来错位的原因。这是我的测试:

PlaygroundPage.current.setLiveView(
    VStack(alignment: .leading) {
        Text("Enter your phone number")
            .border(Color.red, width: 1)
            .font(Font.custom("URWDIN-Thin", size: 30))
        Text("You will be sent a code for verification")
            .border(Color.red, width: 1)
            .font(Font.custom("URWDIN-Thin", size: 16))
        Text("Enter your phone number")
            .border(Color.red, width: 1)
            .font(Font.system(size: 30))
        Text("You will be sent a code for verification")
            .border(Color.red, width: 1)
            .font(Font.system(size: 16))
    }
)

输出:

请注意,在 URW DIN Thin 和系统字体 (SF Pro) 中,大写字母“Y”的左侧方位角基本上为零:两个字形都触及框架的左边缘。

顺丰临的大写字母“E”左侧方位不为零但很小:竖笔画宽度的一小部分。

但是DRW UDM Thin中大写字母“E”的左侧轴承很重要。它大约是垂直笔画宽度的两倍。与大写字母“Y”的零轴承相比,这使得它非常引人注目。