简体   繁体   English

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

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

I'm attempting to align a Text view within a ZStack.我正在尝试在 ZStack 中对齐Text视图。 It works fine for larger screens like the iphone 11 plus max but on smaller screens the text will go off screen if I use trailing or leading alignment like below.它适用于较大的屏幕,例如 iphone 11 plus max,但在较小的屏幕上,如果我使用如下所示的尾随或前导对齐方式,文本将离开屏幕。 I get the same result on the preview, simulator and a real SE device.我在预览、模拟器和真正的 SE 设备上得到了相同的结果。

iPhone SE (2nd gen) Screenshot showing misaligned text for photo attribution text. iPhone SE(第 2 代)屏幕截图显示照片属性文本的未对齐文本。

iPhone SE(第二代截图)

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)
    }
}

I think your code is good, the problem is that your image is too wide and it's overflowing on the right side of the screen.我认为您的代码很好,问题是您的图像太宽并且在屏幕右侧溢出。 The text label is aligning correctly to the trailing of the image (that's why it works on bigger devices), not to the trailing of the screen (what you want).文本标签正确对齐到图像的尾部(这就是它适用于更大设备的原因),而不是屏幕的尾部(你想要的)。

You should make sure your image doesn't overflow.您应该确保您的图像不会溢出。

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

I would use GeomteryReader.我会使用GeomteryReader。 Just like that:就像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM