Search code examples
iosswiftswiftui

How to fill minHeight or minWidth in SwiftUI


Let's say I have the following layout:

VStack {
  Text(title)
    .frame(maxWidth: .infinity, alignment: .leading)

  Spacer()

  Divider()
    .frame(height: 1)
}
.frame(minHeight: 80, alignment: .bottom)

I want the text field to expand freely, divider to be aligned to the bottom, and the whole thing to be at least 80 points tall (but not taller if not necessary). If I leave it like this the spacer will take up all of the parent's height (exceeding 80). If I don't have a spacer, both subviews will be aligned together to the top, bottom, or center.

How can I achieve desired spacer behaviour? Or maybe the layout should be structured differently?


Solution

  • I've figured out a simpler solution for the desired result if I use ZStack instead of spacer like this:

    ZStack(alignment: .bottom) {
      VStack(alignment: .leading) {
        Text(title)
          .frame(maxWidth: .infinity, alignment: .leading)
    
        Text(description)
          .frame(maxWidth: .infinity, alignment: .leading)
      }.frame(minHeight: 80)
    
      Divider()
        .frame(height: 1)
    }
    

    Then, if I want to make sure that the first view in ZStack doesn't overlap the second one, I could use solution proposed by Anton Agafonov and insert a spacer into the VStack with height calculated based on the second child of ZStack.