Why does Text expand when changing contentMode of an Image inside a ZStack?

81 views Asked by At

I have a SwiftUI View that looks like this:

@State var showFullScreen: Bool = false

ZStack {
    Image(uiImage: image)
        .resizable()
        .aspectRatio(contentMode: showFullscreen ? .fill : .fit)
        .padding(showFullscreen ? 0 : 16)
            
    VStack {
        Spacer()
                
        Label("{switchViewsMessage}".localized(), systemImage: "hand.point.up.left.fill")
            .frame(maxWidth: .infinity, alignment: .center)
            .padding()
            .background(bgColor)
            .applyShape(.rounded)
    }
    .padding()
}
.onTapGesture { withAnimation { showFullscreen.toggle() } }
.navigationBarTitle("{photo}".localized())

When the State is set to showFullScreen = false, everything looks like expected. However, when setting showFullScreen to true, the Image changes to .fill to take the whole Screen but also the Text with the Gray Background becomes wider than the Screen.

Why does the Text also expand in Width when changing the State?

1

There are 1 answers

0
Asperi On BEST ANSWER

Is there any way I can still allow the Image to expand while the Text can only fill the available Screen Space?

Use instead the following schema - separate image and text by placing each in own space: image in background, text in overlay, like

Color.clear           // << fills screen space (taking into account safe area
  .background(

     ... your image here

  )
  .overlay(

    VStack {
       ... your text here
    }

  )
  .onTapGesture { withAnimation { showFullScreen.toggle() } }