Declan McKenna
Declan McKenna

Reputation: 4870

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

I'm attempting to align a Text view within a ZStack. 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. I get the same result on the preview, simulator and a real SE device.

iPhone SE (2nd gen) Screenshot showing misaligned text for photo attribution text.

iPhone SE (2nd gen screenshot)

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

Upvotes: 3

Views: 536

Answers (2)

PMT
PMT

Reputation: 1092

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

Upvotes: 4

belotserkovtsev
belotserkovtsev

Reputation: 361

I would use GeomteryReader. Just like that:

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

Upvotes: 2

Related Questions