SwiftUI Child Overflow

Viewed 1170

In SwiftUI, is there a way to have a parent view maintain a fixed size even if the child view is larger? In this example below, the parent grows to fit the contents of the child even if you explicitly set a frame size on the parent:

import SwiftUI

struct ContentView: View {
  var body: some View {
    ZStack {
      ChildView()
      VStack {
        Text("Parent")
        Spacer()
      }
    }
    .frame(width: 100, height: 100)
    .background(Color.red)
    .border(Color.black)
  }
}

struct ChildView: View {
  var body: some View {
    VStack {
      Text("Child")
    }
    .frame(width: 200, height: 200)
    .background(Color.blue)
  }
}

screenshot

I want the "Parent" text to stay within the frame of the parent, but it gets pushed up because the child view is larger.

1 Answers

It is because SwiftUI layout works differently - parent stack fits to content by default. We take ZStack and place in it ChildView and ZStack immediately becomes of its size, then we place VStack in ZStack and Spacer expands it to full size, ie. ChildView's size as it is biggest, then we apply .frame that just generate view of requested size from original ZStack and because it is transparent, by default, we see all content of ZStack. Then we apply border to this resulting view (but still see ZStack's content for same transparency reason)... and so on.

The effect which you want to achieve is

demo

struct ContentView: View {
  var body: some View {
    ZStack {
      ChildView()
      VStack {
        Text("Parent")
        Spacer()
      }
      .frame(width: 100, height: 100)     // << here !!
      .border(Color.black)
    }
    .background(Color.red)
  }
}
Related