如何在 SwiftUI ZStack 中对齐文本以适应较小的屏幕尺寸?

How to align text within a SwiftUI ZStack for smaller screen sizes?

我正在尝试在 ZStack 中对齐 Text 视图。它适用于 iphone 11 plus max 等较大的屏幕,但在较小的屏幕上,如果我使用如下所示的尾部或前导对齐方式,文本将离开屏幕。我在预览、模拟器和真实 SE 设备上得到了相同的结果。

iPhone SE(第 2 代)屏幕截图显示了照片属性文本未对齐的文本。

import SwiftUI

struct ItemDetail: View {
    var item: MenuItem
    var body: some View {
        VStack {
            ZStack(alignment: .bottomTrailing) {
                Image(item.mainImage)
                Text("Photo: \(item.photoCredit)")
                    .padding(4)
                    .font(.caption)
                    .background(Color.black)
                    .foregroundColor(.white)
            }
            Text(item.description)
                .padding()
            Spacer()
        }
        .navigationBarTitle(Text(item.name), displayMode: .inline)
    }
}

我会使用 GeometryReader。就这样:

GeometryReader { geo in
      Text(item.description)          
      .fixedSize(horizontal: false, vertical: true)
      .frame(width: geo.size.width, alignment: .leading)
}

我觉得你的代码很好,问题是你的图片太宽了,溢出到了屏幕的右侧。文本标签正确对齐到图像的尾部(这就是它在更大的设备上工作的原因),而不是屏幕的尾部(你想要的)。

您应该确保您的图像不会溢出。

Image(item.mainImage)
   .resizable()
   .scaleToFit()